Programs make decisions. Python's if/elif/else reads almost like English — but indentation, operator quirks and truthiness hide traps for beginners.
Syntax: if condition: then an indented block; optional elif other: branches; optional final else:. Only the FIRST true branch runs. Comparisons: == != < > <= >=; combine with and / or / not.
age = 13
if age >= 13:
print("Teen coder") # 4-space indent = inside the if
elif age >= 7:
print("Junior coder") # checked only if first was False
else:
print("Future coder") # runs if nothing matched
print("always runs") # not indented = outsidex = 7 print(x == 7) # True (equality: TWO equals signs) print(x != 3) # True print(3 < x <= 10) # True — chaining works in Python! logged_in, admin = True, False print(logged_in and admin) # False — both must be True print(logged_in or admin) # True — one is enough print(not admin) # True — flips the value
items = []
name = "Ada"
if name: # non-empty string → truthy
print(f"hello {name}")
if not items: # empty list → falsy
print("list is empty!")
# Pythonic: use the value itself, not len(items) == 0age = 15 status = "teen" if age >= 13 else "kid" print(status) # teen # great for defaults: name = user_input if user_input else "Guest" name = user_input or "Guest" # even shorter idiom
Deep nesting gets unreadable fast. Flatten with early exits.
def can_play(age, has_ticket):
if age < 7:
return False # early exit — no nesting needed
if not has_ticket:
return False
return True
print(can_play(12, True)) # Trueif x = 5: is a SyntaxError — single = assigns, double == compares: — forgetting it is the most common beginner SyntaxErrorelif checks another condition when previous ones were False; else catches everything that matched nothing — it has no condition.
Yes — the ternary form: result = a if condition else b. For anything longer, use the normal block form for readability.
Unlimited — but if you're chaining many equality checks, a dictionary lookup or match statement (Python 3.10+) is usually cleaner.
Since Python 3.10 there's match/case structural pattern matching, which covers switch use-cases and more.