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)?

10
  • 1
    I missed where you get confused. In the first example? It print y because of the >= 0 part. Commented May 7, 2014 at 7:38
  • I was not expecting the first example to print anything. Commented May 7, 2014 at 7: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. Commented May 7, 2014 at 7:40
  • 3
    Related: How does Python compare string and int? Commented May 7, 2014 at 7:41
  • Even more related. The short answer is: why would you ever want to do such a comparison? It's even fixed in python 3 Commented May 7, 2014 at 7:42

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.