Python Booleans
Python has two boolean values: True and False. They're capitalised, and they're technically a subclass of int (so True == 1).
Truthy / falsy
Any value can be tested for truth. These count as falsy; everything else is truthy:
- The constants
FalseandNone - Zero numbers:
0,0.0,0j - Empty containers:
'',(),[],{},set(),range(0)
Logical operators
| Op | Returns |
|---|---|
x and y | x if x is falsy, otherwise y |
x or y | x if x is truthy, otherwise y |
not x | True if x is falsy, else False |
PYTHON
name = '' print(name or 'anonymous') # 'anonymous' cached = None result = cached or compute() # call compute() only if cache missed
Comparisons can chain
PYTHON
x = 7
if 0 < x < 10:
print('in range')
Tip: Use
is for "same object" (x is None); use == for "same value". For booleans and None always use is — if x is None: is the idiom.Example
Example
print(bool(0), bool(''), bool([]), bool(None)) # all False
print(bool(1), bool('hi'), bool([0]), bool(0.1)) # all True
print(10 > 9, 10 == 9, 10 < 9)
Try it Yourself »
Exercise
Python's "true" constant is spelled…
x =
Capital T; not all-lowercase.
Discussion
Loading…