☼
⌃
☰

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

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

PYTHON
# 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

PYTHON
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

PYTHON
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:

PYTHON
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:

PYTHON
# 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 for over while when the number of iterations is known — it is clearer and less likely to infinite-loop
  • The for-else construct is underused but useful for search-and-not-found patterns — cleaner than a sentinel flag
  • Catching bare Exception is better than except: (which also catches KeyboardInterrupt and SystemExit)
  • Comprehensions are faster than equivalent for loops with append() calls — the C-level implementation avoids the attribute lookup overhead