In the Python console:
>>> a = 0
>>> if a:
... print \"L\"
...
>>> a = 1
>>> if a:
... print \"L\"
...
L
>>&g
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 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
I think it just judges by 0 or not 0:
>>> if 0:
print 'aa'
>>> if not 0:
print 'aa'
aa
>>>
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.