Chapter 5: Control Flow
Direct the execution path of your programs using conditionals and loops.
Downloadchapter5.py
Objectives
- Write
if
,elif
,else
branches. - Create
for
loops over sequences andrange()
. - Use
while
loops for repeated conditions. - Control loops with
break
andcontinue
. - Understand nesting of conditionals and loops.
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:
break
: exit loop immediately.continue
: skip to next iteration.
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
- Write a script that prints numbers 1–20, but stops at the first number divisible by 7.
- Ask the user for a password; keep prompting until they enter the correct one (
"secret"
). - Loop through a list of names and print only those that start with a vowel using
continue
. - Implement a nested loop to print a 5×5 multiplication table.