Conditions & Switches
Python conditional logic with if/elif/else and match/case.
if / elif / else
value = 10
if value > 10:
print("big")
elif value <= 10 and value != 0:
print("medium")
else:
print("small")
Inline (ternary)
result = "amazing" if value > 1 else "not amazing"
Truthiness
These values are falsy: None, False, 0, 0.0, "", [], {}, (), set().
items = []
if not items:
print("empty") # prints
match / case (Python 3.10+)
Pattern matching works on any type:
command = "quit"
match command:
case "start":
print("starting")
case "stop" | "quit":
print("stopping")
case _:
print("unknown")
Matching with guards
match point:
case (x, y) if x == y:
print("diagonal")
case (x, 0):
print(f"on x-axis at {x}")
case _:
print("somewhere")
Next: Collections & Loops