Comparing numbers give the wrong result in Python

You’re testing a string value myAge against another string value '24', as opposed to integer values.

if myAge > ('24'):
     print('You are old, ' + myName)

Should be

if int(myAge) > 24:
    print('You are old, {}'.format(myName))

In Python, you can greater-than / less-than against strings, but it doesn’t work how you might think. So if you want to test the value of the integer representation of the string, use int(the_string)

>>> "2" > "1"
True
>>> "02" > "1"
False
>>> int("02") > int("1")
True

You may have also noticed that I changed print('You are old, ' + myName) to print('You are old, {}'.format(myName)) — You should become accustomed to this style of string formatting, as opposed to doing string concatenation with + — You can read more about it in the docs. But it really doesn’t have anything to do with your core problem.

Leave a Comment