Reputation: 316
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 80 20). However when I give input (50 130 20) it does not work.
What am I doing wrong?
num1=input("Enter 3 numbers\n")
num2=input()
num3=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))
Upvotes: 0
Views: 3796
Reputation: 52
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))
Upvotes: 0
Reputation: 1594
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))
Upvotes: 1