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?
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
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:
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'
0,"",(),{}are considered as False values. - RanRag