Python Control Flow
Conditionals, Loops & Branching
Master the flow of your programs: conditional statements, loops, break/continue/pass, and the new match/case statement. 24 interactive lessons with runnable code β crafted by @PoeticGlenn.
What you will learn
Everything about Python control flow β from basic conditionals to advanced loop control. Learn how to make decisions, repeat actions, and manage program execution with if, for, while, break, continue, pass, else with loops, nested loops, and the powerful match/case pattern matching introduced in Python 3.10. Each concept is broken down step-by-step with interactive code examples from @PoeticGlenn.
Why Control Flow Is the Heart of Programming
Without control flow, programs would be simple sequences of instructions β they couldn't
adapt, repeat, or make decisions. Control flow is what gives your programs intelligence
and flexibility. This curriculum, designed by @PoeticGlenn,
covers every aspect of Python's control flow, from the foundational if statement
to the modern match/case pattern matching, ensuring you can write
dynamic, efficient, and readable code.
Decision Making
Conditionals let your program choose different paths based on data, user input, or state.
Repetition
Loops automate repetitive tasks, process collections, and iterate until conditions are met.
Control
Break, continue, and pass give you fine-grained control over loop execution and program flow.
"The essence of programming is making decisions and repeating tasks β control flow is how we express that." β @PoeticGlenn π
Control Flow Powers Every Dynamic Program
Every program that does anything interesting uses control flow. Whether it's a simple calculator or a complex AI system, the ability to make decisions and repeat actions is fundamental. This curriculum, curated by @PoeticGlenn, ensures you understand not only the syntax but the logic behind each control structure, empowering you to write programs that are both powerful and elegant.
π§ Decision Logic
Master if/elif/else to handle complex conditions and make your programs smarter.
π Iteration Mastery
for and while loops let you process data, repeat tasks, and build efficient algorithms.
π― Fine-Grained Control
break, continue, and pass give you precision in loop management and placeholder logic.
β¨ Modern Pattern Matching
Python 3.10's match/case brings structural pattern matching, making code cleaner and more expressive.
Why Control Flow Is Universal Across All Languages
Every programming language has conditionals and loops. They are the building blocks of algorithms and the foundation of structured programming. Python's control flow is clean, intuitive, and powerful, making it an ideal language for learning and applying these concepts. This curriculum, designed by @PoeticGlenn, gives you transferable skills that apply to any language you learn in the future.
Universal Concepts
Conditionals and loops exist in every language β learn them once, use them everywhere.
Algorithm Foundation
Control flow is the backbone of algorithms β from sorting to searching to AI.
Structural Programming
Control flow structures define the shape and logic of your entire program.
"Control flow is the art of deciding what happens next β and that's what programming is all about."
π Table of Contents
Jump to any section β all entries are equal size
π if, elif, else β Conditional Execution
Make decisions in your code based on boolean conditions.
π 1.1 if Statement
The simplest conditional: execute a block only if the condition is True.
Step-by-step explanation:
- Step 1: Define a condition, e.g.,
age = 18. - Step 2: Write
if age >= 18:. - Step 3: Indent the block to execute when the condition is true.
age = 18 if age >= 18: print("You are an adult.") print("You can vote.")
π 1.2 if/else β Two Paths
Handle both True and False cases.
Step-by-step explanation:
- Step 1: Check
temperature > 30. - Step 2: If true, print hot message; else, print not hot.
temperature = 25 if temperature > 30: print("It's hot outside.") else: print("It's not too hot.")
π 1.3 if/elif/else β Multiple Conditions
Chain multiple conditions with elif.
Step-by-step explanation:
- Step 1: Assign
score = 85. - Step 2: Check conditions from top to bottom.
- Step 3: Execute the first true block.
score = 85 if score >= 90: print("Grade: A") elif score >= 80: print("Grade: B") elif score >= 70: print("Grade: C") elif score >= 60: print("Grade: D") else: print("Grade: F")
π for Loop β Iterating Over Sequences
Iterate over sequences like lists, tuples, strings, and ranges.
π 2.1 Basic for Loop
Iterate over items in a collection.
Step-by-step explanation:
- Step 1: Create a list:
colors = ["red", "green", "blue"]. - Step 2: Use
for color in colors:. - Step 3: Print each color.
colors = ["red", "green", "blue"] for color in colors: print(f"Color: {color}")
π 2.2 range() β Numeric Iteration
range() generates a sequence of numbers for iteration.
Step-by-step explanation:
- Step 1: Use
range(5)to generate 0β4. - Step 2: Use
range(1, 6)for 1β5. - Step 3: Use
range(0, 10, 2)for even numbers.
print("range(5):") for i in range(5): print(i, end=" ") print("\n") print("range(1, 6):") for i in range(1, 6): print(i, end=" ") print("\n") print("range(0, 10, 2):") for i in range(0, 10, 2): print(i, end=" ")
π 2.3 enumerate() β Index and Value
Get both index and value while iterating.
Step-by-step explanation:
- Step 1: Use
enumerate()on a list. - Step 2: Unpack index and value in the loop.
fruits = ["apple", "banana", "cherry"] for index, fruit in enumerate(fruits): print(f"{index}: {fruit}")
β³ while Loop β Repeat Until Condition
Execute a block repeatedly while a condition is true.
π 3.1 Basic while Loop
Use when you don't know the number of iterations in advance.
Step-by-step explanation:
- Step 1: Initialize a counter
count = 0. - Step 2: Write
while count < 5:. - Step 3: Print count and increment.
count = 0 while count < 5: print(f"Count: {count}") count += 1 print("Loop finished!")
False to avoid infinite loops.π 3.2 User Input with while
Keep asking until valid input is received.
Step-by-step explanation:
- Step 1: Set
valid = False. - Step 2: While not valid, ask for input and validate.
valid = False while not valid: response = input("Enter a positive number: ") try: num = float(response) if num > 0: valid = True print(f"Thank you! You entered {num}") else: print("Number must be positive.") except ValueError: print("That's not a valid number.")
βΉοΈ break & continue β Loop Control
Fine-tune loop execution: exit early or skip iterations.
π 4.1 break β Exit the Loop
Terminate the loop immediately.
Step-by-step explanation:
- Step 1: Loop over numbers 1β10.
- Step 2: If number is 5,
break.
for i in range(1, 11): if i == 5: print("Breaking at 5") break print(i)
π 4.2 continue β Skip to Next Iteration
Skip the rest of the current iteration and move to the next.
Step-by-step explanation:
- Step 1: Loop over numbers 0β9.
- Step 2: If number is even,
continue. - Step 3: Print only odd numbers.
for i in range(10): if i % 2 == 0: continue print(i)
π« pass β The Null Statement
Do nothing β use as a placeholder where syntax requires a statement.
π 5.1 Using pass
pass is often used in function stubs, class stubs, and loops that need a placeholder.
Step-by-step explanation:
- Step 1: Define a function that does nothing yet.
- Step 2: Use
passin a loop to skip processing.
def future_function(): pass print("Defined a placeholder function") for i in range(3): if i == 1: pass print(i)
pass is not a comment β it's a valid Python statement that does nothing. It's useful for scaffolding code.π else with Loops β Execute When No break
The else block runs if the loop completes without a break.
π 6.1 for/else and while/else
Useful for search patterns: execute else if item not found.
Step-by-step explanation:
- Step 1: Search for a target in a list.
- Step 2: If found, break. If not, the
elseruns.
items = [1, 2, 3, 4, 5] target = 3 for item in items: if item == target: print(f"Found {target}!") break else: print(f"{target} not found.")
π§© Nested Loops β Loops Inside Loops
Use nested loops to iterate over multi-dimensional data or generate combinations.
π 7.1 Nested for Loops
Iterate over rows and columns of a grid.
Step-by-step explanation:
- Step 1: Outer loop over rows.
- Step 2: Inner loop over columns.
- Step 3: Print a multiplication table.
for i in range(1, 4): for j in range(1, 4): print(f"{i}*{j}={i*j:2}", end=" ") print()
π― match/case β Pattern Matching (Python 3.10+)
Modern and powerful alternative to long if/elif chains for structural pattern matching.
π 8.1 Basic match/case
Match a value against multiple patterns.
Step-by-step explanation:
- Step 1: Use
matchwith a subject. - Step 2: Define
casepatterns. - Step 3: Use
_as wildcard.
def describe_number(n): match n: case 0: return "zero" case 1: return "one" case 2: return "two" case _: return "other" print(describe_number(0)) print(describe_number(2)) print(describe_number(5))
π 8.2 Pattern Matching with Tuples and Guards
Match data structures and add conditions with guards.
Step-by-step explanation:
- Step 1: Match a tuple (x, y).
- Step 2: Use
ifguard for additional condition.
def location(point): match point: case (0, 0): return "origin" case (0, y): return f"on y-axis at {y}" case (x, 0): return f"on x-axis at {x}" case (x, y) if x == y: return f"on diagonal line at ({x}, {y})" case _: return "somewhere else" print(location((0, 0))) print(location((0, 5))) print(location((3, 0))) print(location((3, 3))) print(location((1, 2)))
β Frequently Asked Questions β Python Control Flow
Common questions about control flow in Python, answered.
What is the difference between break and continue?
+break exits the loop entirely, while continue skips the rest of the current iteration and moves to the next one.
When would I use a while loop instead of a for loop?
+Use while when the number of iterations is unknown, such as when waiting for user input or processing data until a condition is met. Use for when iterating over a known sequence.
What does the else clause do in a loop?
+The else block runs if the loop completes without a break. It's useful for search patterns: "if not found, do something".
Is match/case available in all Python versions?
+No, match/case was introduced in Python 3.10. For older versions, use if/elif chains or dictionaries for dispatching.
Can I use pass inside a function?
+Yes, pass is commonly used as a placeholder in functions, classes, or loops that you haven't implemented yet. It prevents syntax errors.
How do I break out of nested loops?
+You can use a flag variable, or wrap the loops in a function and use return. Python doesn't have a "break out of all loops" statement.
What is the difference between if and elif?
+elif is short for "else if". It allows you to check multiple conditions sequentially. Only the first true condition's block executes.
π You've Mastered Python Control Flow
From conditionals to loops, from break to match/case,
you now have a complete understanding of how to direct the flow of your Python programs.
You can make decisions, repeat actions, and handle complex branching with confidence.
This curriculum, crafted by @PoeticGlenn, is your foundation for writing dynamic, responsive, and efficient Python code. The control flow patterns you've learned will serve you in every project, from simple scripts to large-scale applications.
"Control flow is the art of sequencing decisions. Master it, and you master the logic of computation." β Glenn Junsay Pansensoy (@PoeticGlenn)