Control Flow in Python
Control flow determines which statements run, how often they run, and what happens when an operation fails.
Conditional execution
Python evaluates if and elif conditions in order and executes the first matching branch. An optional else handles all remaining cases.
score = 82
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C or below"
print(grade) # B
Values have truth values. Empty containers, numeric zero, None, and False are false; most other objects are true. Prefer direct, readable checks such as if records: over if len(records) > 0:.
for and while loops
Use for to iterate over an iterable:
observations = [3.2, 4.1, 2.7]
for index, value in enumerate(observations, start=1):
print(index, value)
Use while when repetition depends on changing state rather than a known iterable:
value = 40
steps = 0
while value > 1:
value //= 2
steps += 1
print(steps) # 5
break exits the nearest loop. continue skips to its next iteration. A loop's optional else suite runs only when the loop finishes without break.
values = [4, 7, 10]
target = 7
for value in values:
if value == target:
print("found")
break
else:
print("not found")
Exceptions
Catch only errors you can handle, and keep the protected try suite narrow. Catching Exception indiscriminately can hide programming errors.
raw_value = "12"
try:
value = int(raw_value)
except ValueError:
print("not an integer")
else:
print(value * 2) # 24
Use finally for cleanup that must occur whether or not an exception is raised. For files, a context manager is safer and clearer because it closes only a resource that was opened successfully:
from io import StringIO
with StringIO("alpha\nbeta\n") as stream:
first_line = stream.readline().strip()
print(first_line) # alpha
Raise a specific exception when a function's contract is violated.
def divide(numerator, denominator):
if denominator == 0:
raise ValueError("denominator must not be zero")
return numerator / denominator
print(divide(10, 4)) # 2.5