PY

Control Flow

Python · 8 entries

if / elif / else

syntax
if condition:
    ...
elif condition:
    ...
else:
    ...
example
score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"
print(grade)
output
B

Note Python uses indentation instead of braces. There is no switch statement in older Python; use match/case (3.10+) for pattern matching.

Conditional (Ternary) Expression

syntax
value_if_true if condition else value_if_false
example
age = 20
status = "adult" if age >= 18 else "minor"
print(status)

# Nested (use sparingly)
label = "high" if age > 60 else "mid" if age > 30 else "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.

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.

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.

while Loops

syntax
while condition:
    ...
example
attempts = 0
max_attempts = 3

while attempts < max_attempts:
    attempts += 1
    print(f"Try {attempts}")

print("Done")
output
Try 1
Try 2
Try 3
Done

Note Make sure the condition eventually becomes False; otherwise you get an infinite loop. Use Ctrl+C to interrupt a runaway loop.

break & continue

syntax
break    # exit loop
continue # skip to next iteration
example
for n in range(1, 20):
    if n % 7 == 0:
        print(f"Found first multiple of 7: {n}")
        break
    if n % 2 == 0:
        continue
    print(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.

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}")
        break
else:
    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'.

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.