Python - Control Flow

Overview

Estimated time: 30–40 minutes

Control program decisions and repetition with if/elif/else, while/for loops, and the match statement (Python 3.10+).

Learning Objectives

  • Write conditional logic with if/elif/else.
  • Use while and for loops with break/continue correctly.
  • Pattern match basic values with match/case (3.10+).

Prerequisites

if/elif/else

x = 7
if x < 0:
    print("negative")
elif x == 0:
    print("zero")
else:
    print("positive")

Expected Output: positive

for loop

for i in range(3):
    print(i)

Expected Output: 0\n1\n2

while loop and break/continue

n = 0
while True:
    n += 1
    if n == 2:
        continue  # skip 2
    print(n)
    if n == 3:
        break

Expected Output: 1\n3

match/case (3.10+)

status = 404
match status:
    case 200:
        print("OK")
    case 404:
        print("Not Found")
    case _:
        print("Other")

Expected Output: Not Found

Common Pitfalls

  • Off-by-one errors in ranges and loops.
  • Infinite loops from missing update or break condition.

Checks for Understanding

  1. What does continue do inside a loop?
  2. What is the wildcard in match patterns?
Show answers
  1. Skips to the next iteration.
  2. _

Exercises

  1. Print numbers 1..10 skipping multiples of 3 using continue.
  2. Use match/case to print labels for small set of status codes (200, 400, 404, default).