16
votes

In the Python console:

>>> a = 0
>>> if a:
...   print "L"
... 
>>> a = 1
>>> if a:
...   print "L"
... 
L
>>> a = 2
>>> if a:
...   print "L"
... 
L

Why does this happen?

5
That's pretty much true of any scripting language, unless you do a strict comparison to check value AND type. - Marc B
In python 0,"",(),{} are considered as False values. - RanRag

5 Answers

24
votes

In Python, bool is a subclass of int, and False has the value 0; even if values weren't implicitly cast to bool in an if statement (which they are), False == 0 is true.

13
votes

0 is a falsy value in python

Falsy values: from (2.7) documentation:

zero of any numeric type, for example, 0, 0L, 0.0, 0j.

7
votes

Whatever is inside an if clause implicitly has bool called on it. So,

if 1:
   ...

is really:

if bool(1):
   ...

and bool calls __nonzero__1 which says whether the object is True or False

Demo:

class foo(object):
    def __init__(self,val):
        self.val = val
    def __nonzero__(self):
        print "here"
        return bool(self.val)

a = foo(1)
bool(a)  #prints "here"
if a:    #prints "here"
    print "L"  #prints "L" since bool(1) is True.

1__bool__ on python3.x

0
votes

I think it just judges by 0 or not 0:

>>> if 0:
    print 'aa'

>>> if not 0:
    print 'aa'


aa
>>> 
0
votes

First of all, everything in python is an object. Therefore, your 0 is also an object, specifically, a built-in object.

Here are the built-in objects considered as false:

  1. constants defined to be false: None and False.
  2. zero of any numeric type: 0, 0.0, 0j, Decimal(0), Fraction(0, 1)
  3. empty sequences and collections: '', (), [], {}, set(), range(0)

So when you put 0 in an if or while condition, or in a Boolean operation, it is tested for truth value.

# call the __bool__ method of 0
>>> print((0).__bool__())
False

# 
>>> if not 0:
...     print('if not 0 is evaluated as True')
'if not 0 is evaluated as True'