0

Why do those two evaluate differently?

In [34]: a = ''

In [35]: if a or a >=0:
    print 'y'
    ....:     
y

In [36]: a = None

In [37]: if a or a >=0:
    print 'y'
    ....:     

I thought an empty string also evaluates to None (I know they are not the same)? Or is it just falsy and thus evaluates to 0 (which then evaluates to None if tested like if a: do something)?

Bach
  • 6,145
  • 7
  • 36
  • 61
LarsVegas
  • 6,522
  • 10
  • 43
  • 67
  • 1
    I missed where you get confused. In the first example? It print `y` because of the `>= 0` part. – keyser May 07 '14 at 07:38
  • I was not expecting the first example to print anything. – LarsVegas May 07 '14 at 07:40
  • It's because of how string vs int comparison works. The `if a` part doesn't kick in because, as you say, an empty string and `None` is not the same thing. – keyser May 07 '14 at 07:40
  • 3
    Related: [How does Python compare string and int?](http://stackoverflow.com/q/3270680/142637) – sloth May 07 '14 at 07:41
  • [Even more related](http://stackoverflow.com/q/2384078/645270). The short answer is: why would you ever want to do such a comparison? It's even fixed in python 3 – keyser May 07 '14 at 07:42
  • Thanks for the link, indeed very related. I test for empty strings often like `if not x:` instead of `if x !=''`. So i was just adding a condition and then got confused... – LarsVegas May 07 '14 at 07:47
  • @LarsVegas That makes sense. The condition you added kind of doesn't :) – keyser May 07 '14 at 07:48
  • You should use `if a and a >= 0` if you expected the test to behave the same for both values. Or switch to Python 3, where strings and integers are not orderable relative to one another. – Martijn Pieters May 07 '14 at 07:49
  • On Python 3 you'll get `TypeError: unorderable types: str() > int()`. – Matthias May 07 '14 at 07:50
  • @LarsVegas : using `if not x` instead of `if x != ''` is the pythonic idiom (the empty string being False in a boolean context). Your problem comes from comparing oranges and bananas - in this case, either a string or `None` with an integer. – bruno desthuilliers May 07 '14 at 08:44

1 Answers1

0

It's because in CPython int comes before string

from docs:

CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.

so:

>>> '1' > 1
True
Kirill Zaitsev
  • 4,511
  • 3
  • 21
  • 29