Control Flow
Python · Core Language · Run with python3
Explanation
Python's control flow uses `if`/`elif`/`else`, `for` (iterating any iterable), `while`, `break`, `continue`, and `else` clauses on loops (the `else` runs if the loop wasn't broken out of). Conditional expressions (`x if cond else y`) provide ternary-style logic. Python has no `switch`; use `match`/`case` (3.10+) or dicts for dispatch tables.
Real-World Scenario
Searching a list for a target value: use a `for`/`else` — the `else` block only runs if the loop completes without `break`, making "not found" logic explicit without a sentinel variable. ```python # for/else — runs else only if loop wasn't broken def find_prime(n: int) -> bool: for i in range(2, int(n**0.5) + 1): if n % i == 0: break else: return True # No divisor found return False print([x for x in range(2, 20) if find_prime(x)]) # [2, 3, 5, 7, 11, 13, 17, 19] # Conditional expression score = 85 grade = "pass" if score >= 60 else "fail" ```
Quick Snippet
# for/else — runs else only if loop wasn't broken
def find_prime(n: int) -> bool:
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
break
else:
return True # No divisor found
return False
print([x for x in range(2, 20) if find_prime(x)])
# [2, 3, 5, 7, 11, 13, 17, 19]
# Conditional expression
score = 85
grade = "pass" if score >= 60 else "fail"Full Example
# Compile: python3 control_flow.py
# Output:
# [2, 3, 5, 7, 11, 13, 17, 19]
# pass
def is_prime(n: int) -> bool:
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
break
else:
return True # for/else: runs only if loop wasn't broken
return False
primes = [x for x in range(2, 20) if is_prime(x)]
print(primes)
# Conditional expression (ternary)
score = 85
grade = "pass" if score >= 60 else "fail"
print(grade)
# while loop
count = 0
while count < 3:
count += 1
# Nested conditions
x = 42
if x < 0:
print("negative")
elif x == 0:
print("zero")
else:
print("positive")
python3 control_flow.py