0

What would happen if you compare strings with a number? What's happening behind the scenes? Why doesn't this give me an error and instead print "meh" all the time regardless whether the b is within a and c or not?

a = "900"
b = 1055
c = "2000"

if a <=b <= c:
    print "bingo"
else:
    print "meh"

2 Answers2

0

I believe if you compare the strings with the regular numbers, it will instead grab the ASCII values of the characters in the string and compare them via that value. So b would not be less than c, as the ASCII values for the characters in "2000" would be significantly lower than the integer value 1055.

Also, a nicer answer can be found here for the same question.

Community
  • 1
  • 1
Jack Ryan
  • 1,287
  • 12
  • 26
0

in fact, a will be greater than c than b because, python will use the first character as the value in ascii

>>> a > b # ord('9') is 57 which is greater than ord('1') 49
True
>>> a > c # ord('2') is 50, so a is greater because the first '9' value is greater that '2' (57 > 50)
True
>>> c > b # same thing, ord('2') is 50 and ord('1') is 49, so c is greater
True
AkaKaras
  • 102
  • 1
  • 4