iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

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 False and None
  • Zero numbers: 0, 0.0, 0j
  • Empty containers: '', (), [], {}, set(), range(0)

Logical operators

OpReturns
x and yx if x is falsy, otherwise y
x or yx if x is truthy, otherwise y
not xTrue 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 isif 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 =

Test yourself

Q1. Which is FALSY?
Q2. x is None is preferred over…
Q3. True == 1 is…

Discussion

Loading…