Module 04 — Control Flow & Loops
Teaching your program to make decisions and repeat work — if/else, while, and for.
Prerequisite: Module 03 — Strings & User Input
After this lesson, you will be able to
- Branch program logic with if / elif / else and the and/or/not operators
- Repeat code with while loops, including a safe exit condition
- Iterate with for loops and range(), including a step argument
- Control loop flow precisely with break and continue
Concept & Syntax
Control flow is what turns a list of instructions into a program that can actually make
decisions. Two tools do almost all of the work: if statements (decide whether to run some
code) and loops (decide how many times to run some code).
A for loop is used when you know what you're iterating over — a range of numbers, a string, a
list. A while loop is used when you want to repeat "until some condition changes," which might
happen an unpredictable number of times — like re-prompting a user until they type valid input.
if condition:
...
elif other_condition:
...
else:
...
while condition:
...
for item in range(5):
...Examples
if / elif / else Very Easy
age = 20
if age < 13:
print("Child")
elif age < 20:
print("Teenager")
else:
print("Adult")Python checks each condition top to bottom and runs the first block whose condition is True, then skips the rest.
Combining conditions Easy
age = 25
has_id = True
if age >= 18 and has_id:
print("Entry allowed")
else:
print("Entry denied")and requires both sides to be True; or needs only one; not flips a boolean.
while loop with a running total Intermediate
total = 0
n = 1
while n <= 5:
total = total + n
n = n + 1
print(total)The loop keeps running as long as n <= 5 stays True. Each pass adds n to total, then increases n — this is how you sum 1+2+3+4+5.
for loop over a string Easy
for letter in "Py!":
print(letter)A for loop can iterate directly over any sequence — including a string, character by character.
break and continue Real World
for number in range(10):
if number == 7:
break
if number % 2 != 0:
continue
print(number)continue skips straight to the next iteration (skipping odd numbers here); break exits the loop entirely the moment number hits 7.
Visual Explanation
🔍 What happens internally? (advanced)
Under the hood, Python compiles your source into bytecode and runs it on a virtual machine (the CPython interpreter). Variables are names in a namespace dictionary pointing at objects in memory — which is exactly what the memory panel in the tracer above is showing you.
Watch a for loop iterate
Use the controls below to run this example one line at a time and watch the interpreter's memory update live.
Code
for i in range(5):
print(i)
Interpreter state
Console output
Common Mistakes
Forgetting to change the variable a while loop depends on creates an infinite loop that never stops.
n = 1
while n <= 5:
print(n)
# forgot n = n + 1n = 1
while n <= 5:
print(n)
n = n + 1Using = (assignment) instead of == (comparison) inside an if is a very common typo.
age = 18
if age = 18:
print("Just became an adult")age = 18
if age == 18:
print("Just became an adult")- Use
forwhen you know the number of iterations or are iterating over a collection. - Use
whileonly when the stopping condition can't be known in advance. - Keep loop bodies short — extract a function if the logic inside grows past a few lines (the DRY principle: Don't Repeat Yourself).
- Double-check every while loop has a way to eventually become False.
Exercise & Challenge
Exercise 1 — Debug this code
for n in range(9):
if n % 2 = 0:
print(n)This code should print all even numbers from 0 to 8, but it has a bug. What single character needs to change?
🏆 Challenge
Write a program using a while loop that keeps asking the user to 'Enter a number greater than 10' until they succeed, then prints 'Thanks!'.
- Use a while loop with a condition that starts False
- Convert input() to int() before comparing
- Print 'Thanks!' once the loop ends
💡 Need a hint?
Initialize a variable to something that's guaranteed to fail the check the first time, e.g. number = 0.
🔍 Show a sample solution
number = 0
while number <= 10:
number = int(input("Enter a number greater than 10: "))
print("Thanks!")Quiz
Answer every question, then submit to see your score and explanations.
1. What does the DRY principle stand for?
2. What's the difference between break and continue?
3. What does range(5) produce?
4. Which operator checks equality (not assignment)?
5. When should you prefer a for loop over a while loop?
Summary
- if/elif/else branches your program based on conditions, checked top to bottom.
- and, or, and not combine boolean conditions.
- while repeats until a condition becomes False — make sure it eventually does.
- for iterates over a known sequence; break exits early, continue skips ahead.