Part 02 / Topic 4 of 10
Booleans, None and truthiness
boolhas two values:TrueandFalse(capital T and F).Nonemeans "no value yet". Its type isNoneType. Check it withis None.- Truthiness: In an
if, every value acts likeTrueorFalse. (ifruns 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/orreturn one of their operands, not alwaysTrue/False:0 and 5gives0,"" or "Guest"gives'Guest'.boolis a subclass ofint, which is whyTrue + Trueworks.
Done here? The practice set for Part 2 โ 8 exercises with solutions โ is on the part page.