I coded a small project that you can enter two numbers in and it will tell you what’s smaller and what’s bigger, what’s the difference between them and if they’re equal, but the code thinks that 100 is smaller than 50.. I’ve also entered numbers like 50;70 and 60;70, but then it says the correct thing which is that the first number is smaller than the second one. I don’t understand what’s wrong, and how can I fix it? Here’s my code, you can run it yourself so you can see what will happen.
import math
import time
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
difference = num1 - num2
if str(num1) > str(num2):
print("--" + str(num1) + " is greater than " + str(num2) + ".")
print("--The difference between " + str(num1) + " and " + str(num2) + " is " + str(difference) + "." )
elif str(num1) < str(num2):
pass
print("--" + str(num1) + " is smaller than " + str(num2))
print("--The difference cannot be calculated because " + str(num1) + " is smaller than " + str(num2) + ".")
else:
print(str(num1) + " and " + str(num2) + " are equal.")
>Solution :
The problem, as several commenters have pointed out, is that you’re doing a string conversion on the input numbers.
As integers, 50 < 100, but for strings, ordering is done alphabetically – and "1" comes before "5", so "100" < "50".
Drop the str() calls and you should be good.