Site

Control Flow — Python Execution Control

Tutorial 5.0  •  Python / Learn

5.0 What This Teaches

This tutorial covers how Python controls execution flow:

5.1 if / elif / else

score = 78

if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
else:
    print("Below C")   # prints: Below C
Note the colons after each condition and the indented bodies - Python uses indentation to define blocks, not curly braces. There is no then keyword.

5.2 Truthiness

Python evaluates any object as a boolean. Falsy values: 0, 0.0, "", [], {}, None, False. Everything else is truthy:
items = []
if not items:
    print("list is empty")   # idiomatic; no need for len(items) == 0

name = ""
if name:
    print(f"Hello, {name}")
else:
    print("no name given")

count = 42
if count:   # truthy (non-zero)
    print("there are items")

5.3 for Loops

# range(stop), range(start, stop), range(start, stop, step)
for i in range(5):
    print(i, end=" ")   # 0 1 2 3 4

# enumerate gives (index, value) pairs
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

# zip iterates two sequences in parallel
names = ["Alice", "Bob"]
scores = [95, 87]
for name, score in zip(names, scores):
    print(f"{name}: {score}")

5.4 while Loops

n = 1
while n < 100:
    n *= 2
print(n)   # 128

# while True with break for interactive loops
while True:
    response = input("Enter 'quit' to exit: ")
    if response == "quit":
        break
    print(f"You said: {response}")

5.5 break, continue, and for/else

# break exits the loop
for i in range(10):
    if i == 5:
        break
    print(i, end=" ")   # 0 1 2 3 4

# continue skips the rest of the current iteration
for i in range(10):
    if i % 2 == 0:
        continue
    print(i, end=" ")   # 1 3 5 7 9

# for/else: else runs only if loop completed without break
def find_prime(n):
    for divisor in range(2, n):
        if n % divisor == 0:
            print(f"{n} is not prime")
            break
    else:
        print(f"{n} is prime")

5.6 match Statement (Python 3.10+)

command = "quit"

match command:
    case "quit":
        print("Exiting.")
    case "help":
        print("Available commands: quit, help, list")
    case "list":
        print("Nothing in the list.")
    case _:
        print(f"Unknown command: {command}")
match supports more than just literals: you can match on types, sequences, and guard conditions. It is more powerful than a plain if/elif chain.

5.7 Conditional Expression

x = 7
label = "even" if x % 2 == 0 else "odd"
print(label)   # odd

# Inline conditional
abs_val = x if x >= 0 else -x
Python's conditional expression syntax is value_if_true if condition else value_if_false. This reads more naturally than C's condition ? a : b ternary.

5.8 Example - All Together

# Control Flow - fizzbuzz and while convergence.

for i in range(1, 21):
    if i % 15 == 0:
        print("FizzBuzz", end=" ")
    elif i % 3 == 0:
        print("Fizz", end=" ")
    elif i % 5 == 0:
        print("Buzz", end=" ")
    else:
        print(i, end=" ")
print()

# Collatz conjecture: reach 1 from any positive integer
n = 27
steps = 0
while n != 1:
    n = n // 2 if n % 2 == 0 else 3 * n + 1
    steps += 1
print(f"27 reached 1 in {steps} steps")

5.9 Exercise

Exercise
  • Use for with range to print a multiplication table for 7 (7x1 through 7x12).
  • Use while to find the first Fibonacci number greater than 1000. Print it and how many steps it took.
  • Use match on a string variable holding a menu choice ("play", "settings", "quit") and print a different response for each.

5.10 Common Mistakes

Missing colon after if/for/while

if x > 0    # SyntaxError: expected ':'
    print(x)
Every if, elif, else, for, and while header must end with a colon.

Incorrect indentation

Python uses indentation to define blocks. Mixing tabs and spaces, or using inconsistent indentation depth, causes IndentationError or subtle logic bugs. Use 4 spaces per level consistently.

Using = instead of == in conditions

if x = 5:   # SyntaxError - = is assignment, not comparison
    ...
if x == 5:  # correct
Python prevents accidental assignment in conditions - unlike C, this is a syntax error.

5.11 Key Terms

TermMeaning
if / elif / elseConditional branching; condition can be any truthy value
truthinessEmpty containers, 0, None, and False are falsy; everything else truthy
forIterates any iterable: list, range, string, dict, file, etc.
range()Generates a sequence of integers for use in for loops
enumerate()Wraps an iterable to yield (index, value) pairs
zip()Combines multiple iterables into pairs (or n-tuples)
whileRepeats while condition is true
breakExits the enclosing loop
continueSkips the rest of the current iteration
matchPython 3.10+ structural pattern matching
conditional expressionvalue_if_true if condition else value_if_false