Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 02 / Topic 4 of 10

Booleans, None and truthiness

  • bool has two values: True and False (capital T and F).
  • None means "no value yet". Its type is NoneType. Check it with is None.
  • Truthiness: In an if, every value acts like True or False. (if runs the indented lines only when the condition is true. It is taught fully in Part 3; here we just use it to test values.)
Falsy (act like False) Truthy (act like True)
False, None, 0, 0.0, "", and empty containers [], {}, (), set() (Part 4) Everything else, e.g. 1, -5, "0", " ", [0]

Real-world example: Check if a customer entered a coupon code.

coupon = ""
if coupon:
    print("Coupon applied")
else:
    print("No coupon")      # No coupon

discount = None
print(discount is None)     # True
print(bool(0), bool("0"), bool(" "))  # False True True
print(True + True)          # 2   (True is 1, False is 0)

name = ""
print(name or "Guest")       # Guest  (`or` gives back the first truthy value)

๐Ÿ” Going deeper: and / or return one of their operands, not always True/False: 0 and 5 gives 0, "" or "Guest" gives 'Guest'. bool is a subclass of int, which is why True + True works.

Done here? The practice set for Part 2 โ€” 8 exercises with solutions โ€” is on the part page.

Search the guide