Part 03 / Stage 1
Control flow
Goal: Make your programs take decisions and repeat work using
if,match,whileandfor. Time: ~1 hour
What you will learn
if/elif/elseand nestedif- The one-line conditional expression (
x if c else y) match/case: literals, OR patterns|, wildcard_, capture and guardwhileloops andforloopsrange(start, stop, step)break,continueandpass- The
elseblock on loops enumerate()andzip()for cleaner loops- Common loop patterns: counter, accumulator, search
Topics in this part
Practice
Python workbench โ write and run code here
Press Run and Python 3.14 loads right in your browser (a one-time download of about 15 MB; after that it works offline). Your code never leaves this page. input() opens a small prompt window.
Try each one yourself first. Put the sample values straight into your code (no input()), so the program runs without typing anything.
Some exercises loop over a small list like [7, -4, 0] with for (lists are covered in Part 4).
Exercise 1: Even, odd and sign checker
Scenario: A maths quiz app needs to describe a number.
What to do: Loop over numbers = [7, -4, 0]. For each number print, for example, 7 is positive and odd. Zero should give 0 is zero and even.
Sample output:
7 is positive and odd
-4 is negative and even
0 is zero and even
๐ก Hint: Use if/elif/else for the sign and a conditional expression with n % 2 == 0 for even/odd.
Show the solution to Exercise 1
"""Exercise 1: Even, odd and sign checker.
Run: python ex01.py (macOS/Linux: python3 ex01.py)
"""
numbers = [7, -4, 0]
for n in numbers:
if n > 0:
sign = "positive"
elif n < 0:
sign = "negative"
else:
sign = "zero"
parity = "even" if n % 2 == 0 else "odd" # conditional expression
print(f"{n} is {sign} and {parity}")
Exercise 2: Electricity bill (slab rates)
Scenario: The electricity board charges by slabs.
What to do: Loop over readings = [80, 150, 320] and print the bill for each, using these rates:
| Units | Rate |
|---|---|
| first 100 | โน3 per unit |
| next 100 (101โ200) | โน5 per unit |
| above 200 | โน8 per unit |
Sample output:
80 units -> โน240
150 units -> โน550
320 units -> โน1,760
๐ก Hint: For 150 units: 100 ร 3 + 50 ร 5. Handle each slab in an if/elif/else. Print the amount with f"โน{amount:,}" to get the comma in โน1,760 (Part 2).
Show the solution to Exercise 2
"""Exercise 2: Electricity bill with slab rates.
Run: python ex02.py (macOS/Linux: python3 ex02.py)
"""
readings = [80, 150, 320]
for units in readings:
if units <= 100:
amount = units * 3
elif units <= 200:
amount = 100 * 3 + (units - 100) * 5
else:
amount = 100 * 3 + 100 * 5 + (units - 200) * 8
print(f"{units} units -> โน{amount:,}")
Exercise 3: FizzBuzz
Scenario: A classic counting game from school.
What to do: Count from 1 to 15. Print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, else the number.
Sample output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
๐ก Hint: Check "multiple of 15" first. Order matters in if/elif.
Show the solution to Exercise 3
"""Exercise 3: FizzBuzz from 1 to 15.
Run: python ex03.py (macOS/Linux: python3 ex03.py)
"""
for n in range(1, 16):
if n % 15 == 0: # check "both" first
print("FizzBuzz")
elif n % 3 == 0:
print("Fizz")
elif n % 5 == 0:
print("Buzz")
else:
print(n)
Exercise 4: Day planner with match
Scenario: A calendar app shows a message for each day.
What to do: Loop over days = ["sun", "tue", "fri", "abc"] and use match to pick a message:
"sat"or"sun"โ"Weekend: relax!""fri"โ"Last working day""mon","tue","wed","thu"โ"Working day"- anything else โ
"Unknown day: <day>"
Sample output:
sun -> Weekend: relax!
tue -> Working day
fri -> Last working day
abc -> Unknown day: abc
๐ก Hint: Use OR patterns case "sat" | "sun": and the wildcard case _:.
Show the solution to Exercise 4
"""Exercise 4: Day planner with match-case.
Run: python ex04.py (macOS/Linux: python3 ex04.py)
"""
days = ["sun", "tue", "fri", "abc"]
for day in days:
match day.lower():
case "sat" | "sun":
message = "Weekend: relax!"
case "fri":
message = "Last working day"
case "mon" | "tue" | "wed" | "thu":
message = "Working day"
case _:
message = f"Unknown day: {day}"
print(f"{day} -> {message}")
Exercise 5: Digit tools with while
Scenario: A bank checks account numbers using their digits.
What to do: For number = 4721, find the sum of its digits and the number reversed, using a while loop (no strings).
Sample output:
Digit sum of 4721: 14
Reverse of 4721: 1274
๐ก Hint: n % 10 gives the last digit and n // 10 removes it. Copy number into n first, then loop while n > 0.
Show the solution to Exercise 5
"""Exercise 5: Digit sum and reverse using a while loop.
Run: python ex05.py (macOS/Linux: python3 ex05.py)
"""
number = 4721
n = number # work on a copy, keep `number` for printing
digit_sum = 0 # accumulator
reversed_number = 0
while n > 0:
last_digit = n % 10
digit_sum += last_digit
reversed_number = reversed_number * 10 + last_digit
n //= 10 # drop the last digit
print(f"Digit sum of {number}: {digit_sum}")
print(f"Reverse of {number}: {reversed_number}")
Exercise 6: Prime finder with loop else
Scenario: A puzzle app needs all prime numbers up to 30.
What to do: For each number from 1 to 30, check if it is prime using an inner for loop with break and else. Print the primes on one line.
Sample output:
Primes up to 30: 2 3 5 7 11 13 17 19 23 29
๐ก Hint: Skip numbers below 2 with continue. Try divisors with range(2, int(n ** 0.5) + 1): up to the square root, and the + 1 makes sure the square root itself is tested (so 25 is not called prime). If one divides n, break. The loop else means "no divisor found", so print the number with end=" ".
Show the solution to Exercise 6
"""Exercise 6: Prime finder using for + break + loop-else.
Run: python ex06.py (macOS/Linux: python3 ex06.py)
"""
print("Primes up to 30:", end=" ")
for n in range(1, 31):
if n < 2:
continue # 0 and 1 are not prime
# Try divisors up to the square root. The + 1 is needed because
# range() stops before its end, and we must also test the root itself
# (25 -> 2..5, so 5 is tested and 25 is not called prime).
# For huge numbers, math.isqrt(n) is exact (import is taught in Part 7).
for divisor in range(2, int(n ** 0.5) + 1):
if n % divisor == 0:
break # found a divisor, not prime
else:
print(n, end=" ") # no break: n is prime
print()
Exercise 7: Number guessing game (simulated)
Scenario: A game picks a secret number. The player gets at most 5 guesses.
What to do: Use secret = 42 and guesses = [50, 25, 200, 40, 42] (instead of input()).
- For each guess print
Too low,Too highorCorrect! Got it in N tries. - Skip (with
continue) any guess outside 1โ100, printingIgnored: <guess>. It still uses up a try. - Stop after 5 tries. If not guessed, print
Out of tries. The number was <secret>. - Check: with
guesses = [1, 2, 3, 4, 5, 6, 42]the last line should beOut of tries. The number was 42(after try 5).
Sample output:
Try 1: 50 -> Too high
Try 2: 25 -> Too low
Try 3: Ignored: 200
Try 4: 40 -> Too low
Try 5: 42 -> Correct! Got it in 5 tries
๐ก Hint: for attempt, guess in zip(range(1, 6), guesses): numbers the tries and stops after 5. Use break on a correct guess and a loop else for "out of tries".
Show the solution to Exercise 7
"""Exercise 7: Number guessing game (guesses come from a list).
Run: python ex07.py (macOS/Linux: python3 ex07.py)
"""
MAX_TRIES = 5
secret = 42
guesses = [50, 25, 200, 40, 42] # try [1, 2, 3, 4, 5, 6, 42] for "out of tries"
# zip stops at the shorter one, so only the first MAX_TRIES guesses count
for attempt, guess in zip(range(1, MAX_TRIES + 1), guesses):
if guess < 1 or guess > 100: # outside 1-100
print(f"Try {attempt}: Ignored: {guess}")
continue
if guess < secret:
print(f"Try {attempt}: {guess} -> Too low")
elif guess > secret:
print(f"Try {attempt}: {guess} -> Too high")
else:
print(f"Try {attempt}: {guess} -> Correct! Got it in {attempt} tries")
break
else:
print(f"Out of tries. The number was {secret}")
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
if x = 5: |
= assigns, it does not compare |
use == |
Missing : after if, for, while |
SyntaxError |
always end the line with : |
| Mixed or missing indentation | IndentationError or wrong logic |
use 4 spaces for every block |
while condition never changes |
infinite loop | update the variable inside the loop |
Expecting range(1, 5) to include 5 |
stop is excluded |
use range(1, 6) |
case n: or case _: placed before other cases |
it matches everything, so Python stops with a SyntaxError ("makes remaining patterns unreachable") |
put capture / _ last |
Thinking loop else means "if loop was empty" |
it means "no break happened" |
use it only for search-style loops |
if age > 18 and < 60 |
each side needs a full comparison | if age > 18 and age < 60: or if 18 < age < 60: |
if day == "sat" or "sun": |
"sun" alone is always truthy, so this is always True |
if day == "sat" or day == "sun": |
Quick recap
if / elif / elsepicks the firstTruebranch.a if cond else bis a one-line choice that gives back a value.match / casecompares one value with many patterns;_is the default.forloops over items;whileloops until a condition isFalse.range(start, stop, step)never includesstop.breakstops,continueskips,passdoes nothing.- Loop
elseruns only when there was nobreak. enumerategives index + item;zippairs two lists.
Checklist
- I can write an
if / elif / elsechain with the right order of conditions. - I can use a conditional expression for a short choice.
- I can write a
matchwith literals,|,_and a guard. - I can choose between
forandwhile. - I can use
rangewith a step, including counting down. - I can use
break,continueand loopelsefor a search. - I can loop with
enumerateandzip. - I can write counter, accumulator and search loops.