Number comparison to find max/min in python

后端 未结 3 1976
再見小時候
再見小時候 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: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))
    

提交回复
热议问题