Skip to content
  • Control Flow · Python

Control Flow

LearnViaNotes @learnvianotes· 2 min read

if/elif/else, for, while, match — plus a few Python-only twists like for … else.

Conditionals

Python
def grade(score):
    if score >= 90:
        return "A"
    elif score >= 75:
        return "B"
    else:
        return "C"

print(grade(95), grade(80), grade(40))       # A B C
status = "adult" if 20 >= 18 else "minor"     # conditional expression
print(status)                                  # adult

Loops

for iterates over any iterable (lists, strings, dicts, files, generators). while repeats while a condition is truthy.

Python
for i in range(2, 10, 3):          # start, stop (exclusive), step
    print(i, end=" ")               # 2 5 8
print()
for i, ch in enumerate("abc", start=1):
    print(i, ch, end=" | ")         # 1 a | 2 b | 3 c |
print()
for name, age in zip(["a", "b"], [20, 30]):
    print(name, age, end="; ")      # a 20; b 30;
HelperGives youInstead of
enumerate(it)(index, item) pairsfor i in range(len(xs))
zip(a, b)Items side by side (stops at the shortest)Manual index juggling
reversed(seq)Items back to front, lazilyseq[::-1] (copies)
sorted(it, key=…)A new sorted listSorting then copying

break, continue and loop else

A loop's else block runs only if the loop finished without break — perfect for search loops.

Python
def find_first_negative(nums):
    for i, n in enumerate(nums):
        if n < 0:
            break
    else:
        return None          # no break → nothing found
    return i

print(find_first_negative([3, 1, -2, 5]))   # 2
print(find_first_negative([1, 2]))          # None

match — structural pattern matching (3.10+)

Python
def describe(cmd):
    match cmd:
        case ["go", direction]:
            return f"moving {direction}"
        case ["pick", *items] if items:
            return f"picking {len(items)} items"
        case {"action": "quit"}:
            return "bye"
        case int() | float() as n:
            return f"number {n}"
        case _:
            return "unknown"

print(describe(["go", "north"]))       # moving north
print(describe(["pick", "a", "b"]))    # picking 2 items
print(describe({"action": "quit"}))    # bye
print(describe(3.5))                   # number 3.5

No do … while, no ++

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report