Control Flow
Table of Contents
Determines the order in which statements execute. Without control flow, programs run sequentially top to bottom. Branches, loops, and early exits allow programs to respond to data and conditions.
Related: Python Python Functions
Conditionals
Python
x = 42 if x > 100: print("large") elif x > 10: print("medium") else: print("small") # Ternary (conditional expression) label = "even" if x % 2 == 0 else "odd" # Match statement (Python 3.10+) match command: case "quit": exit() case "help": show_help() case _: print("unknown command")
Loops
For loops
# Iterate over a sequence fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) # Range 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 — index + value for i, fruit in enumerate(fruits): print(i, fruit) # Zip — parallel iteration for a, b in zip([1, 2, 3], ["x", "y", "z"]): print(a, b)
While loops
count = 0 while count < 5: print(count) count += 1 # Infinite loop with explicit break while True: data = input("Enter command: ") if data == "quit": break process(data)
Loop control
for i in range(10): if i == 3: continue # skip to next iteration if i == 7: break # exit the loop entirely print(i) # else on a loop — runs if loop completes without break for item in collection: if condition(item): result = item break else: result = None # loop exhausted without finding item
Exception Handling
Control flow for error conditions:
try: result = int(user_input) data = fetch_data(url) except ValueError: print("Not a valid number") except (ConnectionError, TimeoutError) as e: print(f"Network error: {e}") except Exception as e: print(f"Unexpected error: {e}") raise # re-raise to propagate else: print("Success") # runs only if no exception finally: cleanup() # always runs
List/Dict/Set Comprehensions
Concise control flow for building collections:
# List comprehension squares = [x**2 for x in range(10)] evens = [x for x in range(20) if x % 2 == 0] # Dict comprehension word_lengths = {word: len(word) for word in words} # Set comprehension unique_lengths = {len(word) for word in words} # Generator expression — lazy (not a comprehension, no brackets) total = sum(x**2 for x in range(1000000)) # no list created
Tips
- Prefer
foroverwhilewhen the number of iterations is known — it is clearer and less likely to infinite-loop - The
for-elseconstruct is underused but useful for search-and-not-found patterns — cleaner than a sentinel flag - Catching bare
Exceptionis better thanexcept:(which also catchesKeyboardInterruptandSystemExit) - Comprehensions are faster than equivalent
forloops withappend()calls — the C-level implementation avoids the attribute lookup overhead