Number comparison to find max/min in python

后端 未结 3 1975
再見小時候
再見小時候 2021-01-28 04:51

I am a beginner in python. I have written a simple program to find greatest of 3 numbers. I get the right answer when I give input numbers having same number of digits (Eg. 50 8

相关标签:
3条回答
  • 2021-01-28 05:31

    You can find the maximum of any number of numbers with max

    print "The greatest number is " + max(int(num1), int(num2), int(num3))
    
    0 讨论(0)
  • 2021-01-28 05:37

    You are yet another victim of dynamic typing.

    When you read in data to your num variables, the variables are treated as strings.

    When Python compares two strings using the < or > operator, it does so lexicographically -- meaning alphabetically. Here's a few examples.

    'apple' < 'orange' //true
    'apple' < 'adam' //false
    '6' < '7' //true as expected
    '80' < '700' //returns false, as 8 > 7 lexiographically
    

    Therefore, you want to convert your input using int(), so < comparisons work as expected.

    Code

    num1=int("Enter 3 numbers\n")
    num2=int(input())
    num3=int(input())
    if(num1 > num2):
        if(num1 > num3):
            print("The greatest number is "+ str(num1))
        else:
            print("the greatest number is "+ str(num3))
    else:
        if(num2 > num3):
            print("The greatest number is " + str(num2))
        else:
            print("The greatest number is " + str(num3))
    
    0 讨论(0)
  • 2021-01-28 05:42

    If you don't want TimTom's (no max()), here is another way:

    num1= int("Enter 3 Number\n")
    num2= int(input())
    num3= int(input())
    
    if num1 >= num2 and num1 >= num3:
       numLarge = num1
    #  print exchange
    elif num2 >= num1 and num2 >= num3:
       numLarge = num2
    #  print exchange
    else:
       numLarge = num3
    #  print exchange
    
    print("The greatest is " + str(numLarge))
    
    0 讨论(0)
提交回复
热议问题