Issue
I'm trying to create a program in python that will determine which number is bigger from two user inputted numbers. For some reason, python is telling me that the smaller number is greater than the larger number. It seems to work correctly if I input only single digit numbers or only double digit numbers, but not if I input a single and a double digit number.
a=input("Enter an int:\n")
b=input("Enter another int:\n")
if a>b:
print(a+" is greater than " + b)
elif b>a:
print(b+" is greater than " + a)
If I input 10 for a and 3 for b then I get the output: 3 is greater than 10
If I input 6 for a and 2 for b then I get the output: 6 is greater than 2
If I input 24 for a and 10 for b then I get the output: 24 is greater than 10
Why does it not work with a single and a double digit?
Solution
Python's built-in input() function always returns a str(string) class object. Therefore, for taking integer input, we have to type cast those inputs into integers by using the built-in function int(). See revised below:
a=int(input("Enter an int:\n"))
b=int(input("Enter another int:\n"))
However, in order to let the print statements work, you have to adjust them as well. Now you are trying to make a joint string from a string and an integer, which will lead to an TypeError. Therefore, you can try:
if a>b:
print("{} is greater than {}".format(a,b))
elif b>a:
print("{} is greater than {}".format(b,a))
So the full code will be:
a=int(input("Enter an int:\n"))
b=int(input("Enter another int:\n"))
if a>b:
print("{} is greater than {}".format(a,b))
elif b>a:
print("{} is greater than {}".format(b,a))
Answered By - Isa-Ali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.