Branch on a condition or repeat an action.
if/elif/else is a fork in the road; for/while is a conveyor belt.
if cond: --True--> branch A
--else--> branch B
for x in seq:
body; break / continue
else: # runs ONLY if no break fired
Whitespace-significant. Comprehensions beat for+append (faster in C). The walrus := (PEP 572) assigns inside an expression to avoid duplicate work. The rarely-used for/else runs only on a clean exit - perfect for search loops.
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n,'=',x,'*',n//x); break
else: # no break
print(n,'is prime')
rare for/else - else runs only when loop completes WITHOUT break.
while (line := input('> ')) != 'quit':
print(f'echo: {line}')
walrus := assigns and checks in one expression.
matches = [m for m in items if m.score >= 90]
print(matches or 'no high scorer')
list comprehension is idiomatic; or provides a default if empty.
Mutating a list while iterating it directly (for x in lst: lst.remove(x)) silently skips elements. Iterate over lst[:] or build a fresh list.
Use comprehensions; for/else for ‘not found’; walrus only when it removes a duplicate expression.
for row in rows: if row.expired: rows.remove(row) skips indices.rows = [r for r in rows if not r.expired].