3.1 Control Flow Fundamentals
Python control flow uses indentation-based blocks and clear statement forms.
if / elif / else
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
for loops
Python for iterates over iterable objects directly.
for word in ["cat", "window", "defenestrate"]:
print(word, len(word))
range()
range() creates an immutable arithmetic progression, commonly used in loops.
for i in range(0, 10, 2):
print(i)
while, break, continue, loop else
breakexits the nearest loop.continuejumps to next iteration.- Loop
elseruns when nobreakoccurs.
Official references
- Control flow tutorial: https://docs.python.org/3/tutorial/controlflow.html
- Compound statements reference: https://docs.python.org/3/reference/compound_stmts.html