On this page
article
Control Flow
Master Python control flow — conditional statements, for and while loops, break/continue, and list, dict, and set comprehensions.
Control flow determines which code runs and how many times. Python provides conditionals, loops, and comprehensions for expressive program logic.
Conditional Statements
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Grade: {grade}")
Ternary Expression
status = "pass" if score >= 60 else "fail"
Truthiness in Conditions
name = ""
if name: # empty string is falsy
print(name)
else:
print("Anonymous")
items = [1, 2, 3]
if items: # non-empty list is truthy
print(f"{len(items)} items")
For Loops
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
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 and Zip
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
names = ["Alice", "Bob"]
ages = [25, 30]
for name, age in zip(names, ages):
print(f"{name} is {age}")
Looping Over Dictionaries
user = {"name": "Alice", "age": 30, "city": "NYC"}
for key in user:
print(key)
for key, value in user.items():
print(f"{key}: {value}")
While Loops
count = 0
while count < 5:
print(count)
count += 1
break, continue, else
for n in range(10):
if n == 3:
continue # skip 3
if n == 7:
break # stop at 7
print(n)
else:
print("Loop completed without break")
# while with else
num = 10
while num > 0:
num -= 1
else:
print("Countdown finished")
List Comprehensions
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
matrix = [[0] * 3 for _ in range(3)]
# flatten
flat = [x for row in matrix for x in row]
Dictionary Comprehensions
word_lengths = {word: len(word) for word in ["hello", "world", "python"]}
# {'hello': 5, 'world': 5, 'python': 6}
filtered = {k: v for k, v in word_lengths.items() if v > 5}
Set Comprehensions
unique_lengths = {len(word) for word in ["hello", "world", "hi", "python"]}
# {2, 5, 6}
Generator Expressions
Memory-efficient alternative to list comprehensions:
total = sum(x**2 for x in range(1_000_000)) # no list created
match/case (Python 3.10+)
Structural pattern matching:
def handle_command(command):
match command.split():
case ["quit"]:
return "Goodbye!"
case ["load", filename]:
return f"Loading {filename}"
case ["save", filename]:
return f"Saving {filename}"
case ["greet", name, *rest]:
return f"Hello, {name}!"
case _:
return "Unknown command"
print(handle_command("greet Alice"))
print(handle_command("load data.csv"))
Practical Example
def fizzbuzz(n):
results = []
for i in range(1, n + 1):
if i % 15 == 0:
results.append("FizzBuzz")
elif i % 3 == 0:
results.append("Fizz")
elif i % 5 == 0:
results.append("Buzz")
else:
results.append(str(i))
return results
# Comprehension version
fizzbuzz = lambda n: [
"FizzBuzz" if i % 15 == 0 else
"Fizz" if i % 3 == 0 else
"Buzz" if i % 5 == 0 else str(i)
for i in range(1, n + 1)
]
Control flow is the backbone of program logic. Next: Functions & Modules.