Python evaluates 0 as False

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.


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


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.

Tags:

Python

Boolean