Python comparison operator not giving proper answer in if-else statements

48 Views Asked by At
# Program1: Take two numbers as input from User and print which one is greater or are they equal.

num1 = input("Enter the first number: ")
num2 = input("Enter the second number: ")
if num1 is num2:
    print("The two numbers are equal")
elif num1 < num2:
    print("The first number is less than the second number")
else:
    print("The first number is greater than the second number")


Enter the first number: -10 Enter the second number: -20 The first number is less than the second number

Process finished with exit code 0

What is wrong in above code to compare two numbers? How come python missing basic -ve number comparison?

3

There are 3 best solutions below

2
tho On

In your case you should use '==' statement instead of 'is' statement.

'==' actually compare the value where 'is' check if they are same object.

See a previous discussion about that

0
Ada On

You are doing a string comparison, not a numerical comparison. The string "-10" does come before "-20" since "1" comes before "2" in lexicographical order. To do an integer comparison you should cast the values you receive to int:

num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
0
Raky On

First, input() returns string. SO you need to cast the input values to integer by using int().

Second, when you use if num1 is num2:, the is operator(keyword) is testing if num1and num2refer to the same object or not.

Third, Enter the first number: -10 Enter the second number: -20 The first number is less than the second number

Process finished with exit code 0

You know that -10 and -20 are numbers, but as mentioned in First Para above, input()is returning string values, python is doing lexicographical comparison, and ascii of - is highter than digit.

So, your code should be like this instead

num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

if num1 == num2:
    print("The two numbers are equal")
elif num1 < num2:
    print("The first number is less than the second number")
else:
    print("The first number is greater than the second number")