5.0 What This Teaches
if/elif/elseand truthinessforloops withrange,enumerate, andzipwhileloopsbreak,continue, and thefor/elsepatternmatchstatements (Python 3.10+)- Conditional expressions (ternary)
5.1 if / elif / else
score = 78
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("Below C") # prints: Below C
then keyword.
5.2 Truthiness
0,
0.0, "", [], {}, None,
False. Everything else is truthy:
items = []
if not items:
print("list is empty") # idiomatic; no need for len(items) == 0
name = ""
if name:
print(f"Hello, {name}")
else:
print("no name given")
count = 42
if count: # truthy (non-zero)
print("there are items")
5.3 for Loops
# range(stop), range(start, stop), range(start, stop, step)
for i in range(5):
print(i, end=" ") # 0 1 2 3 4
# enumerate gives (index, value) pairs
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
# zip iterates two sequences in parallel
names = ["Alice", "Bob"]
scores = [95, 87]
for name, score in zip(names, scores):
print(f"{name}: {score}")
5.4 while Loops
n = 1
while n < 100:
n *= 2
print(n) # 128
# while True with break for interactive loops
while True:
response = input("Enter 'quit' to exit: ")
if response == "quit":
break
print(f"You said: {response}")
5.5 break, continue, and for/else
# break exits the loop
for i in range(10):
if i == 5:
break
print(i, end=" ") # 0 1 2 3 4
# continue skips the rest of the current iteration
for i in range(10):
if i % 2 == 0:
continue
print(i, end=" ") # 1 3 5 7 9
# for/else: else runs only if loop completed without break
def find_prime(n):
for divisor in range(2, n):
if n % divisor == 0:
print(f"{n} is not prime")
break
else:
print(f"{n} is prime")
5.6 match Statement (Python 3.10+)
command = "quit"
match command:
case "quit":
print("Exiting.")
case "help":
print("Available commands: quit, help, list")
case "list":
print("Nothing in the list.")
case _:
print(f"Unknown command: {command}")
match supports more than just literals: you can match on types,
sequences, and guard conditions. It is more powerful than a plain if/elif chain.
5.7 Conditional Expression
x = 7
label = "even" if x % 2 == 0 else "odd"
print(label) # odd
# Inline conditional
abs_val = x if x >= 0 else -x
value_if_true if condition else value_if_false.
This reads more naturally than C's condition ? a : b ternary.
5.8 Example - All Together
# Control Flow - fizzbuzz and while convergence.
for i in range(1, 21):
if i % 15 == 0:
print("FizzBuzz", end=" ")
elif i % 3 == 0:
print("Fizz", end=" ")
elif i % 5 == 0:
print("Buzz", end=" ")
else:
print(i, end=" ")
print()
# Collatz conjecture: reach 1 from any positive integer
n = 27
steps = 0
while n != 1:
n = n // 2 if n % 2 == 0 else 3 * n + 1
steps += 1
print(f"27 reached 1 in {steps} steps")
5.9 Exercise
Exercise
- Use
forwithrangeto print a multiplication table for 7 (7x1 through 7x12). - Use
whileto find the first Fibonacci number greater than 1000. Print it and how many steps it took. - Use
matchon a string variable holding a menu choice ("play", "settings", "quit") and print a different response for each.
5.10 Common Mistakes
Missing colon after if/for/while
if x > 0 # SyntaxError: expected ':'
print(x)
if, elif, else, for,
and while header must end with a colon.Incorrect indentation
IndentationError or
subtle logic bugs. Use 4 spaces per level consistently.
Using = instead of == in conditions
if x = 5: # SyntaxError - = is assignment, not comparison
...
if x == 5: # correct
5.11 Key Terms
| Term | Meaning |
|---|---|
| if / elif / else | Conditional branching; condition can be any truthy value |
| truthiness | Empty containers, 0, None, and False are falsy; everything else truthy |
| for | Iterates any iterable: list, range, string, dict, file, etc. |
| range() | Generates a sequence of integers for use in for loops |
| enumerate() | Wraps an iterable to yield (index, value) pairs |
| zip() | Combines multiple iterables into pairs (or n-tuples) |
| while | Repeats while condition is true |
| break | Exits the enclosing loop |
| continue | Skips the rest of the current iteration |
| match | Python 3.10+ structural pattern matching |
| conditional expression | value_if_true if condition else value_if_false |