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?
Python assigns boolean values to values of other types. For numerical types like integers and floating-points, zero values are false and non-zero values are true. For strings, empty strings are false and non-empty strings are true.
The Python Boolean type is one of Python's built-in data types. It's used to represent the truth value of an expression. For example, the expression 1 <= 2 is True , while the expression 0 == 1 is False . Understanding how Python Boolean values behave is important to programming well in Python.
The following are falsy values in Python: The number zero ( 0 ) An empty string '' False.
First, we look at what kind of values evaluate to "True" or "False" in python. Anything that is "empty" usually evaluates to False, along with the integer 0 and the boolean value of False. Objects that are not empty evaluate to "True", along with numbers not equal to 0, and the boolean value True.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With