Python Control Flow — Core Concepts
Conditionals
if / elif / else
Python’s conditional structure is standard:
score = 75
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
Python evaluates conditions top-to-bottom and executes the first matching block. Subsequent conditions are skipped — even if they would also be true.
Truthiness
Python has a concept of “truthy” and “falsy” values. In any boolean context, many values evaluate to False:
None0,0.0- Empty sequences:
"",[],(),{} - Objects that define
__bool__returningFalse
Everything else is truthy. This lets you write concise conditions:
items = []
if not items:
print("Nothing in the list")
name = "Alice"
if name:
print(f"Hello, {name}")
Ternary Expression
Python has a one-line conditional expression (often called “ternary”):
label = "Adult" if age >= 18 else "Minor"
Use it for simple value selection. Avoid nesting it — deeply nested ternaries are unreadable.
Loops
for Loops
Python’s for iterates over any iterable — lists, strings, ranges, dictionaries, files, and anything else that implements iteration:
# Over a list
for fruit in ["apple", "banana", "cherry"]:
print(fruit)
# Over a string
for char in "Python":
print(char)
# Over a 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)
range() generates numbers on demand without storing them all in memory — an important detail for large ranges.
Common Patterns
Enumerate — when you need both index and value:
items = ["a", "b", "c"]
for i, item in enumerate(items):
print(f"{i}: {item}")
# 0: a
# 1: b
# 2: c
Zip — iterate over two sequences together:
names = ["Alice", "Bob"]
scores = [92, 87]
for name, score in zip(names, scores):
print(f"{name}: {score}")
while Loops
while repeats as long as a condition is true:
attempts = 0
while attempts < 3:
guess = input("Guess the number: ")
if guess == "42":
print("Correct!")
break
attempts += 1
Use while when you don’t know ahead of time how many iterations you need. Use for when you’re iterating over a collection or a known range.
Loop Control
break
Exits the loop immediately:
for n in range(100):
if n == 7:
break # Stop here, don't continue
continue
Skips to the next iteration:
for n in range(10):
if n % 2 == 0:
continue # Skip even numbers
print(n) # Prints 1, 3, 5, 7, 9
else on Loops (Python-Unique)
Python lets you attach else to a loop. It runs when the loop finishes without hitting a break:
for item in items:
if item == target:
print("Found it!")
break
else:
print("Not found") # Only runs if break never hit
This pattern cleanly handles “search and report” logic. Most Python developers don’t know about it; the ones who do use it regularly.
The Walrus Operator (:=)
Introduced in Python 3.8, := assigns a value and evaluates it in the same expression:
import re
if m := re.search(r"\d+", text):
print(f"Found number: {m.group()}")
Without walrus:
m = re.search(r"\d+", text)
if m:
print(f"Found number: {m.group()}")
The walrus version is more concise, particularly useful in while loops reading chunks of data:
with open("large_file.txt") as f:
while chunk := f.read(8192):
process(chunk)
match / case (Python 3.10+)
Python 3.10 added structural pattern matching — similar to switch statements in other languages, but more powerful:
command = "quit"
match command:
case "quit":
exit()
case "go" | "move":
move_player()
case _:
print(f"Unknown command: {command}")
It works on complex structures too:
match point:
case (0, 0):
print("Origin")
case (x, 0):
print(f"X-axis at {x}")
case (0, y):
print(f"Y-axis at {y}")
case (x, y):
print(f"Point at ({x}, {y})")
Common Misconception: for Loops Are Only for Lists
Python’s for works on any iterable, including database query results, file lines, network streams, and custom objects. Anything that implements __iter__ and __next__ works.
for line in open("data.txt"): # Reads one line at a time
process(line)
This reads one line at a time without loading the entire file into memory — critical for large files.
One Thing to Remember
Python loops (
forandwhile) can have anelseclause that runs when nobreakoccurred — it’s one of the language’s most underused features, and it’s perfect for “search and report” logic.
See Also
- Python Async Await Async/await helps one Python program juggle many waiting jobs at once, like a chef who keeps multiple pots moving without standing still.
- Python Basics Python is the programming language that reads like plain English — here's why millions of beginners (and experts) choose it first.
- Python Booleans Make Booleans click with one clear analogy you can reuse whenever Python feels confusing.
- Python Break Continue Make Break Continue click with one clear analogy you can reuse whenever Python feels confusing.
- Python Closures See how Python functions can remember private information, even after the outer function has already finished.