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
You can find the maximum of any number of numbers with max
print "The greatest number is " + max(int(num1), int(num2), int(num3))
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))
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))