Control Flow Beginner¶
When you'd use this
if/elif/else, for loops, while loops and match-case.
Use conditionals and loops to make decisions and repeat work — validating input, iterating over data, retrying until a condition holds, dispatching on a value.
Conditionals¶
Branch on a condition with if/elif/else. Use it to validate input, pick a code path, or map a value to a category.
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("F")
Ternary (one-liner)¶
Truthy and Falsy values¶
# Falsy: False, None, 0, 0.0, "", [], {}, set()
# Everything else is Truthy
if []: print("never") # empty list is falsy
if [1, 2, 3]: print("yes!") # non-empty list is truthy
if "": print("never") # empty string is falsy
if "hello": print("yes!")
for Loops¶
Iterate over any sequence or range. Pair with enumerate when you need the index and zip to walk two sequences together.
# Iterate over a sequence
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Range
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(2, 10, 2): # 2, 4, 6, 8
print(i)
# Enumerate — get index AND value
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# 0: apple
# 1: banana
# 2: cherry
# Zip — iterate two lists together
names = ["Alice", "Bob", "Charlie"]
scores = [95, 87, 72]
for name, score in zip(names, scores):
print(f"{name}: {score}")
# Alice: 95
# Bob: 87
# Charlie: 72
while Loops¶
Repeat until a condition changes — when you don't know the iteration count up front (input loops, polling, retries). Use break to exit early and continue to skip an iteration.
count = 0
while count < 5:
print(count)
count += 1
# break — exit the loop early
while True:
answer = input("Type 'quit' to exit: ")
if answer == "quit":
break
print(f"You said: {answer}")
# continue — skip to next iteration
for i in range(10):
if i % 2 == 0:
continue # skip even numbers
print(i) # prints 1, 3, 5, 7, 9
match-case (Python 3.10+)¶
Structural pattern matching — cleaner than a long if/elif chain when dispatching on a value or the shape of data. See the Pattern Matching deep dive for destructuring.
command = "quit"
match command:
case "quit":
print("Quitting...")
case "help":
print("Showing help...")
case "start" | "run": # multiple patterns
print("Starting...")
case _: # default (wildcard)
print(f"Unknown: {command}")
Loop else clause¶
Runs only if the loop finished without hitting break — handy for "searched everything and found nothing" logic.
# else runs only if the loop completed without break
for i in range(5):
if i == 10:
break
else:
print("Loop finished normally") # this prints
Practice exercises¶
- Write a program that prints all numbers 1–100. For multiples of 3 print "Fizz", multiples of 5 print "Buzz", multiples of both print "FizzBuzz".
- Use a
whileloop to find the first power of 2 greater than 1000. - Write a number guessing game: generate a random number 1–100, let the user guess with "higher"/"lower" hints.
- Use
match-caseto build a simple command dispatcher.
💬 Discussion
Have a question about this topic? Found an error? Share your thoughts below.