Control Flow and Iteration
When first learning Python, the part that's easiest to "know how to write but hard to write smoothly" is often not the syntax itself, but not having stable templates in your head for controlling flow. This page collects the most common patterns for conditionals, loops, and iteration.
Conditional Statements
The most basic structure is if / elif / else:
score = 86
if score >= 90:
level = "A"
elif score >= 80:
level = "B"
else:
level = "C"
Get a feel for truthiness
Python doesn't just use True and False for conditions -- many objects have inherent truth values:
if []:
print("this won't run")
if "hello":
print("a non-empty string is treated as True")
Common falsy values:
FalseNone00.0""[]{}set()
for Loop
Python encourages "iterating over objects directly" rather than grabbing indices first like in C.
for name in ["alice", "bob", "charlie"]:
print(name)
If you want both the element and its position, use enumerate():
names = ["alice", "bob", "charlie"]
for index, name in enumerate(names, start=1):
print(index, name)
If you need to iterate over multiple sequences in parallel, use zip():
names = ["alice", "bob"]
scores = [92, 85]
for name, score in zip(names, scores):
print(name, score)
while Loop
while is better suited for "condition-driven" loops, such as continuous reading, retrying, or accumulating.
count = 0
while count < 3:
print(count)
count += 1
A common pitfall
If you forget to update the condition variable in the loop body, you'll enter an infinite loop:
while count < 3:
print(count)
# forgot to write count += 1
break, continue, pass
for number in range(10):
if number == 3:
continue
if number == 7:
break
print(number)
break: Ends the entire loop immediately.continue: Skips the current iteration and moves to the next.pass: A placeholder that does nothing.
List Comprehensions
Many "loop + condition + collect results" patterns can be rewritten as list comprehensions:
numbers = [1, 2, 3, 4, 5, 6]
even_squares = [x * x for x in numbers if x % 2 == 0]
This pattern is very common, but don't overuse it. Once the expression gets too long or deeply nested, it's clearer to fall back to a regular loop.
My common selection criteria
- Already know you need to iterate over something: prefer
for - Need both element and index:
enumerate() - Iterate multiple sequences in parallel:
zip() - Need to keep trying until a condition is met:
while - Just constructing a new list: consider a list comprehension first