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

Python evaluates 0 to False

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 is this happening?

+6
source share
4 answers

In Python, bool is a subclass of int , and False is 0 ; even if the values ​​were not explicitly specified in the bool in the if (what they are), False == 0 - true.

+14
source

0 - false value in python

False values: from (2.7) documentation:

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

+12
source

Everything inside the if clause implicitly calls bool . Thus,

 if 1: ... 

really:

 if bool(1): ... 

and bool calls __nonzero__ 1 which indicates 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__ in python3.x

+6
source

I think it just judges 0 or not 0:

 >>> if 0: print 'aa' >>> if not 0: print 'aa' aa >>> 
+1
source

Source: https://habr.com/ru/post/925773/


All Articles