Python Control Flow Cheat Sheet: if, for, while, match
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
| Task | Code | Result |
|---|---|---|
| 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 equal | 10 >= 10 | True |
| Not equal | "a" != "b" | True |
| Both conditions (and) | age >= 18 and has_id | True |
| Either condition (or) | age < 13 or age > 65 | False |
| Negate (not) | not has_id | False |
| Chained range check | 18 <= age < 30 | True |
| Default with or | name or "guest" | 'guest' |
| Check None correctly | value is None | True |
| Even or odd | "even" if 7 % 2 == 0 else "odd" | 'odd' |
| Leap year test | (2024 % 4 == 0 and 2024 % 100 != 0) or 2024 % 400 == 0 | True |
Python truthy and falsy values cheat sheet
| Task | Code | Result |
|---|---|---|
| Zero is falsy | bool(0) | False |
| Non-zero number is truthy | bool(-3) | True |
| Empty string is falsy | bool("") | False |
| Text "False" is truthy | bool("False") | True |
| Empty list is falsy | bool([]) | False |
| Empty dict is falsy | bool({}) | False |
| None is falsy | bool(None) | False |
| and returns the first falsy value | 3 and 0 and 5 | 0 |
| or returns the first truthy value | 0 or [] or "x" | 'x' |
| not always returns a bool | not "hello" | False |
| Compare with == not truthiness | 0 == False | True |
| any and all on lists | any([0, "", 5]), all([1, "a"]) | (True, True) |
Python for loop and range cheat sheet
| Task | Code | Result |
|---|---|---|
| Count 0 to 4 | list(range(5)) | [0, 1, 2, 3, 4] |
| Count 1 to 5 | list(range(1, 6)) | [1, 2, 3, 4, 5] |
| Step by 2 | list(range(0, 10, 2)) | [0, 2, 4, 6, 8] |
| Count down | list(range(5, 0, -1)) | [5, 4, 3, 2, 1] |
| Loop over a list | for fruit in ["apple", "kiwi"]: print(fruit) | apple, kiwi |
| Loop over a string | for ch in "abc": print(ch, end="") | abc |
| Index and value | list(enumerate(["a", "b"])) | [(0, 'a'), (1, 'b')] |
| Two lists together | list(zip([1, 2, 3], ["x", "y"])) | [(1, 'x'), (2, 'y')] |
| Sum in a loop | for n in [4, 5]: t += n | 9 |
| Reverse a loop | list(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
| Task | Code | Result |
|---|---|---|
| Basic while loop | while i < 4: total += i; i += 1 | 6 |
| break exits the loop | for n in [1, 2, 3, 4]: print(n); break | 1 |
| continue skips an item | [n for n in range(5) if n != 2] | [0, 1, 3, 4] |
| Find first match | next(n for n in [3, 8, 5, 12] if n > 6) | 8 |
| Default when nothing matches | next((n for n in [1, 2] if n > 6), None) | None |
| break vs continue vs pass | pass | pass does nothing, a placeholder |
| Loop with else | else: # runs if no break | the else of a loop runs only when the loop was not stopped by break |
| Infinite loop with exit | while True: break | no output |
| Accumulate until a limit | while t < 10: t += 4 | 12 |
| 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 digits | sum(int(d) for d in str(1234)) | 10 |
Python match statement and conditional patterns
| Task | Code | Result |
|---|---|---|
| Match a value | match code: case 200: ... | runs the first case whose value equals code |
| Several values in one case | case 401 | 403: | matches either value |
| Wildcard default | case _: | matches anything, so put it last |
| Match a sequence | case [x, y]: | matches a two-item list and binds x, y |
| Match a dict shape | case {"kind": k}: | matches any dict that has a kind key |
| Guard with if | case 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 ors | 5 in (1, 5, 9) | True |
Python common control flow programs
| Task | Code | Result |
|---|---|---|
| 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 |
| Factorial | math.factorial(5) | 120 |
| Fibonacci step | a, b = b, a + b | from 0, 1 this yields 0, 1, 1, 2, 3, 5, 8, 13 |
| GCD | math.gcd(48, 18) | 6 |
| Armstrong check for 153 | sum(int(d) ** 3 for d in "153") == 153 | True |
| Star pattern row | "*" * 3 | '***' |
| Linear search | [4, 7, 9].index(7) | 1 |
| Largest of three | max(3, 9, 4) | 9 |
| Average | sum([4, 6, 8]) / 3 | 6.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.
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.
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 →