Time to give your programs a brain! 🧠 In Modules 1–3, your code ran in a straight line. Now you’ll make it choose paths (like “if the player has a key, open the door”) and repeat actions (like “keep asking until the answer is correct”). This is called control flow — and it’s where coding gets really fun!
if 🚦
The if statement runs some code only when a condition is True.
The condition is just a boolean expression (remember Module 3!).
Notice the colon : and the indentation (4 spaces) —
they’re required!
{ }) to know which lines belong inside the if.
Use 4 spaces every time.
if / else 🔀
What if you want something to happen when the condition is False?
Add an else block. Only one of the two blocks will run.
elif 🎚️
elif means “else if”. Use it to test more conditions in order.
Python checks each one from top to bottom and runs the first match it finds, then skips the rest.
>= 70 first,
even a 95 would get a C!
while 🔁
A while loop keeps running as long as its condition is True.
Perfect for things like “keep asking until the user types the right password”.
countdown -= 1).
for & range() 🔢
A for loop repeats code a set number of times.
The range() function generates a sequence of numbers for you.
It’s cleaner than while when you know how many times to loop.
| Code | Gives you |
|---|---|
range(5) | 0, 1, 2, 3, 4 |
range(1, 6) | 1, 2, 3, 4, 5 |
range(0, 10, 2) | 0, 2, 4, 6, 8 |
break & continue 🚪
Sometimes you need to exit a loop early (break) or skip one turn (continue).
Here’s how they work inside a game-style loop:
break = quit the game. continue = skip to the next level.
Here’s a tiny number-guessing game that uses while, if/elif/else, and break.
(We’ll use input() here — it asks the player to type something!)
guess.py and run it. Notice how the loop keeps going until break runs.
FizzBuzz is a famous coding challenge. Create a file called fizzbuzz.py. Loop through the numbers 1 to 20 and:
%).
💡 Hint: Check for “both” first using n % 3 == 0 and n % 5 == 0.
Bonus: use continue to skip printing the number in some cases!