Note Python uses indentation instead of braces. There is no switch statement in older Python; use match/case (3.10+) for pattern matching.
if elseconditionalelifbranchternary
Conditional (Ternary) Expression
syntax
value_if_true if condition else value_if_false
example
age = 20
status = "adult"if age >= 18else"minor"print(status)
# Nested (use sparingly)
label = "high"if age > 60else"mid"if age > 30else"young"print(label)
output
adult
young
Note Nested ternaries hurt readability fast. If you need more than one level, use a regular if/elif chain instead.
ternary operatorinline ifconditional expressionone line if
match / case (Structural Pattern Matching)
syntax
match subject:
case pattern:
...
example
command = {"action": "move", "x": 10, "y": 20}
match command:
case {"action": "move", "x": x, "y": y}:
print(f"Moving to ({x}, {y})")
case {"action": "stop"}:
print("Stopping")
case _:
print("Unknown command")
output
Moving to (10, 20)
Note match/case (Python 3.10+) is structural pattern matching, not just a switch. It can destructure dicts, sequences, and objects in the pattern.
match casepattern matchingswitch statementstructural matching
for Loops
syntax
for item in iterable:
...
example
total = 0
prices = [12.50, 8.99, 24.00]
for price in prices:
total += price
print(f"Total: ${total:.2f}")
for i in range(3):
print(f"Attempt {i + 1}")
output
Total: $45.49
Attempt 1
Attempt 2
Attempt 3
Note range(n) produces 0 through n-1. Use range(start, stop, step) for more control. Python for loops iterate over any iterable, not just numeric ranges.
Note Make sure the condition eventually becomes False; otherwise you get an infinite loop. Use Ctrl+C to interrupt a runaway loop.
while looploop until conditionrepeat untilinfinite loop
break & continue
syntax
break# exit loopcontinue# skip to next iteration
example
for n in range(1, 20):
if n % 7 == 0:
print(f"Found first multiple of 7: {n}")
breakif n % 2 == 0:
continueprint(f"Odd: {n}")
output
Odd: 1
Odd: 3
Odd: 5
Found first multiple of 7: 7
Note break exits only the innermost loop. To break out of nested loops, refactor into a function and use return.
break loopcontinue loopskip iterationexit loop early
else Clause on Loops
syntax
for item in iterable:
...
else:
# runs if loop completed without break
example
targets = [2, 4, 6, 8]
for num in targets:
if num % 5 == 0:
print(f"Found multiple of 5: {num}")
breakelse:
print("No multiple of 5 found")
output
No multiple of 5 found
Note The else block runs only if the loop was NOT terminated by break. This is one of Python's most misunderstood features. Think of it as 'no-break'.
for elseloop else clauseno breakloop completed
Walrus Operator (:=)
syntax
if (name := expression):
example
data = [5, 12, 3, 18, 7, 22]
high = [x for x in data if (doubled := x * 2) > 20]
print(high)
import re
text = "Order #12345 confirmed"if (match := re.search(r"#(\d+)", text)):
print(f"Order ID: {match.group(1)}")
output
[12, 18, 22]
Order ID: 12345
Note The walrus operator (Python 3.8+) assigns and returns a value in one step. Most useful in while-loops, if-statements, and comprehensions to avoid repeated computation.
walrus operatorassignment expression:= operatorassign and check