Cheat sheetCore Python

Python Control Flow Cheat Sheet: if, for, while, match

Short answer
Python control flow uses if/elif/else to choose, for and while to repeat, break and continue to steer loops, and match (Python 3.10+) to branch on the shape of a value.

Control flow decides which lines run and how often. The tables here cover decisions, truthiness, loops, loop control and pattern matching, with the real output of every line that can be run on one line. Longer blocks are described in words.

For the full explanations see if...else, for loops and while loops.

Python if, elif and else cheat sheet

Assume `age = 20`, `has_id = True`, `name = ""` and `value = None`. Conditions evaluate to `True` or `False`, and `if` runs its block on `True`.
TaskCodeResult
Basic if / else as one line"pass" if 72 >= 40 else "fail"'pass'
Grade with elif chain"A" if 91 >= 90 else "B" if 91 >= 80 else "C"'A'
Greater than or equal10 >= 10True
Not equal"a" != "b"True
Both conditions (and)age >= 18 and has_idTrue
Either condition (or)age < 13 or age > 65False
Negate (not)not has_idFalse
Chained range check18 <= age < 30True
Default with orname or "guest"'guest'
Check None correctlyvalue is NoneTrue
Even or odd"even" if 7 % 2 == 0 else "odd"'odd'
Leap year test(2024 % 4 == 0 and 2024 % 100 != 0) or 2024 % 400 == 0True

Python truthy and falsy values cheat sheet

TaskCodeResult
Zero is falsybool(0)False
Non-zero number is truthybool(-3)True
Empty string is falsybool("")False
Text "False" is truthybool("False")True
Empty list is falsybool([])False
Empty dict is falsybool({})False
None is falsybool(None)False
and returns the first falsy value3 and 0 and 50
or returns the first truthy value0 or [] or "x"'x'
not always returns a boolnot "hello"False
Compare with == not truthiness0 == FalseTrue
any and all on listsany([0, "", 5]), all([1, "a"])(True, True)

Python for loop and range cheat sheet

TaskCodeResult
Count 0 to 4list(range(5))[0, 1, 2, 3, 4]
Count 1 to 5list(range(1, 6))[1, 2, 3, 4, 5]
Step by 2list(range(0, 10, 2))[0, 2, 4, 6, 8]
Count downlist(range(5, 0, -1))[5, 4, 3, 2, 1]
Loop over a listfor fruit in ["apple", "kiwi"]: print(fruit)apple, kiwi
Loop over a stringfor ch in "abc": print(ch, end="")abc
Index and valuelist(enumerate(["a", "b"]))[(0, 'a'), (1, 'b')]
Two lists togetherlist(zip([1, 2, 3], ["x", "y"]))[(1, 'x'), (2, 'y')]
Sum in a loopfor n in [4, 5]: t += n9
Reverse a looplist(reversed([1, 2, 3]))[3, 2, 1]
Multiplication table row[3 * i for i in range(1, 6)][3, 6, 9, 12, 15]
Nested loops[(r, c) for r in range(2) for c in range(2)][(0, 0), (0, 1), (1, 0), (1, 1)]

Python while loop, break and continue cheat sheet

TaskCodeResult
Basic while loopwhile i < 4: total += i; i += 16
break exits the loopfor n in [1, 2, 3, 4]: print(n); break1
continue skips an item[n for n in range(5) if n != 2][0, 1, 3, 4]
Find first matchnext(n for n in [3, 8, 5, 12] if n > 6)8
Default when nothing matchesnext((n for n in [1, 2] if n > 6), None)None
break vs continue vs passpasspass does nothing, a placeholder
Loop with elseelse: # runs if no breakthe else of a loop runs only when the loop was not stopped by break
Infinite loop with exitwhile True: breakno output
Accumulate until a limitwhile t < 10: t += 412
Countdown[n for n in range(3, 0, -1)][3, 2, 1]
Digits of a number[int(d) for d in str(1234)][1, 2, 3, 4]
Sum of digitssum(int(d) for d in str(1234))10

Python match statement and conditional patterns

TaskCodeResult
Match a valuematch code: case 200: ...runs the first case whose value equals code
Several values in one casecase 401 | 403:matches either value
Wildcard defaultcase _:matches anything, so put it last
Match a sequencecase [x, y]:matches a two-item list and binds x, y
Match a dict shapecase {"kind": k}:matches any dict that has a kind key
Guard with ifcase n if n > 5:matches only when the guard is true
Lookup table alternative{"a": 1, "b": 2}.get("b", 0)2
Ternary for two outcomes"yes" if 3 > 2 else "no"'yes'
Nested if flattened with and(5 > 1 and 5 < 9)True
Membership instead of many ors5 in (1, 5, 9)True

Python common control flow programs

TaskCodeResult
FizzBuzz for 15"FizzBuzz" if 15 % 15 == 0 else 15'FizzBuzz'
Is a number prime?n > 1 and all(n % d for d in range(2, int(n ** 0.5) + 1))True
Factorialmath.factorial(5)120
Fibonacci stepa, b = b, a + bfrom 0, 1 this yields 0, 1, 1, 2, 3, 5, 8, 13
GCDmath.gcd(48, 18)6
Armstrong check for 153sum(int(d) ** 3 for d in "153") == 153True
Star pattern row"*" * 3'***'
Linear search[4, 7, 9].index(7)1
Largest of threemax(3, 9, 4)9
Averagesum([4, 6, 8]) / 36.0

Examples you can run

Press Run, then edit the code and run it again.

Loop with if, continue and break

Print odd numbers and stop at the first number above 7.

Loop with if, continue and break
for n in range(1, 12):
    if n % 2 == 0:
        continue
    if n > 7:
        break
    print(n)
Expected output1
3
5
7

Classify values with match

match picks the first case that fits; _ is the default.

Classify values with match
def kind(code):
    match code:
        case 200 | 201:
            return "success"
        case 404:
            return "missing"
        case _:
            return "other"

print(kind(201), kind(404), kind(500))
Expected outputsuccess missing other

Python Control Flow Cheat Sheet: if, for, while, match: questions people ask

What is the difference between break and continue in Python?

break ends the whole loop immediately, while continue skips the rest of the current iteration and moves to the next one.

Does Python have a switch statement?

Python 3.10 added the match statement, which works like a switch and also matches patterns such as lists and dicts. Before that, people used if/elif chains or dictionaries.

What does the else on a Python for loop do?

The else block runs only when the loop finishes without hitting break. It is handy for search loops that need a "not found" branch.

Keep learning

Step-by-step lessons:
Python if, elif and elsePython for LoopsPython while Loops

Related:
Python Cheat Sheet (Python 3.13 Quick Reference)Python Functions Cheat Sheet: def, args, lambda, scopePython break vs continue vs pass: DifferencesPython FizzBuzz ProgramPython Truthy and Falsy Values

More in core python:
Python Cheat Sheet (Python 3.13 Quick Reference)Python String Cheat Sheet: Methods and FormattingPython List Cheat Sheet: Methods and ExamplesPython Dictionary Cheat Sheet: Methods and ExamplesPython Functions Cheat Sheet: def, args, lambda, scopePython OOP Cheat Sheet: Classes, Inheritance, Dunder MethodsPython Regex Cheat Sheet (re Module Quick Reference)Python File Handling Cheat Sheet: open, read, write, CSV, JSON See all →