-2
if "16" > "13": print("a")
if "8" > "15": print("b")

This code will print "a b" in the console. Why does the first statement work as intended and the second doesn't?

Nicolas Othmar
  • 144
  • 1
  • 12

2 Answers2

2

In Python, the > and < operators are implemented using a class's underlying __cmp__ magic function, the logic of which differs by class.

The logic for numbers is to compare the signed value, e.g. 12.6 >10 is true, and -4 > -33.02 is true, in the normal mathematical sense.

The logic for strings is to compare each character, left to right, based on the ordinal value of each character, e.g. 'apple' > 'banana' is false because ord('a') is 97 and ord('b') is 98, so 97 > 98 is false. Likewise '8 > '15' is true because ord('8') is 56, and and ord('1') is 49, so 56 > 49 is true.

Python doesn't convert strings-of-digits to numbers before comparing.

Chris Johnson
  • 20,650
  • 6
  • 81
  • 80
0

Because 8 (first digit) is greater than 1 (first digit)... you are comparing strings, not integers.

Do you want to compare numbers? Do the same without the quotes:

if 16 > 13: print("a")
if 8 > 15: print("b")
mcsoini
  • 6,280
  • 2
  • 15
  • 38