Chapter 5: Control Flow

Direct the execution path of your programs using conditionals and loops.

Download chapter5.py

Objectives

1. Conditional Statements

Branch logic based on boolean expressions:

x = 10
if x < 5:
    print("x is less than 5")
elif x < 15:
    print("x is between 5 and 14")
else:
    print("x is 15 or more")

You can nest conditions:

score = 85
if score >= 90:
    grade = "A"
else:
    if score >= 80:
        grade = "B"
    else:
        grade = "C"
print(f"Grade: {grade}")

2. for Loops

Iterate over sequences (lists, strings, ranges):

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# using range()
for i in range(5):       # 0,1,2,3,4
    print(i)

You can also loop with index:

for idx, val in enumerate(fruits, start=1):
    print(idx, val)

3. while Loops

Repeat while a condition holds true:

count = 0
while count < 3:
    print("Count is", count)
    count += 1

Use a sentinel or flag to control the loop:

running = True
while running:
    cmd = input("Enter command (quit to exit): ")
    if cmd == "quit":
        running = False
    else:
        print("You typed:", cmd)

4. break & continue

Alter loop execution flow:

for n in range(10):
    if n == 5:
        break        # stops loop at 5
    print(n)

for n in range(5):
    if n % 2 == 0:
        continue     # skip even numbers
    print(n)         # prints 1,3

Exercises

  1. Write a script that prints numbers 1–20, but stops at the first number divisible by 7.
  2. Ask the user for a password; keep prompting until they enter the correct one ("secret").
  3. Loop through a list of names and print only those that start with a vowel using continue.
  4. Implement a nested loop to print a 5×5 multiplication table.