Reputation: 31
I'm a beginner to Python. I have written code to find the greatest of 3 numbers which is working fine other than these numbers 100,10,20 which are provided as input. I'm getting the output as "The largest number is 20" but my expectation is is should be "The largest number is 100" My code is as follows:
a = input("Enter 1st value")
b = input("Enter 2nd value")
c = input("Enter 3rd value")
if (a > b) and (a > c):
lnum = a
elif (b > a) and (b > c):
lnum = b
else:
lnum = c
print("The largest number is", lnum)
Can anyone help me to understand why the output is showing 20 as greatest instead of 100?
Upvotes: 1
Views: 102
Reputation: 12322
Your inputs are strings and are sorted by comparing the characters left to right.
Comparing "100" against "20" first compares "1" and "2". "1" is smaller so your code picks "20" as the larger value.
As others have mentioned if you convert the input to integer using int(input('Enter 1st value ')
then it will work as you intended and there is a max()
function you can use.
Note: There still is another mistake in your code:
Enter 1st value20
Enter 2nd value20
Enter 3rd value10
('The largest number is', 10)
The check for (b > a)
is wrong and causes you to output c if a == b.
Upvotes: 0
Reputation: 672
You could do this easier with max(list)
when you store your values in a list. Example:
values = []
values.append(int(input('Enter 1st value ')))
values.append(int(input('Enter 2st value ')))
values.append(int(input('Enter 3st value ')))
lnum = max(values)
print("The largest number is", lnum)
Upvotes: 0
Reputation: 17322
you have to convert your inputs to int
:
a = input("Enter 1st value")
b = input("Enter 2nd value")
c = input("Enter 3rd value")
print("The largest number is", max(map(int, (a, b, c))))
Upvotes: 0
Reputation: 127
a = input("Enter 1st value")
stores string into a
you should convert it into integer by using int()
method.
a = int(input("Enter 1st value"))
or try a= input("Enter 1st value")
then a=int(a)
.
Upvotes: 0
Reputation: 2453
Your variables are strings, you must convert them to ints like this:
a = int(input('Enter 1st value'))
Upvotes: 8