Learning goals
Repeat work with for and while, control a loop, and package repeated logic in a function.
Explanation
A for loop visits items from an iterable. range(start, stop, step) provides integers and excludes stop. A while loop repeats while its condition is truthy. Ensure something changes so a while loop can finish.
break exits the nearest loop. continue skips the rest of the current iteration. pass does nothing; it is a placeholder, not another spelling of continue. Nested loops complete the inner loop for each outer item.
Example 1 Repetition and control
count = 1
while count <= 3:
print("Count:", count)
count += 1
for number in range(1, 7):
if number == 2:
continue
if number == 5:
break
print("Accepted:", number)
for row in range(1, 3):
for column in range(1, 3):
print(row, column)Output: Count lines for 1, 2, 3; Accepted lines for 1, 3, 4; then coordinate pairs 1 1, 1 2, 2 1, 2 2. break at 5 prevents 5 and 6 from being printed.
Functions primer
A function is a reusable block defined with def. Parameters name its inputs; arguments are the actual values passed by a caller. return sends a result back and ends the call. A function without a return value returns None. A local variable normally belongs to that call.
Example 2 Reusable calculations
def total_price(quantity, unit_price, discount=0):
subtotal = quantity * unit_price
return subtotal * (1 - discount)
print(total_price(3, 100))
print(total_price(3, 100, discount=0.1))
def sum_values(*values):
return sum(values)
print(sum_values(2, 3, 4))Expected output: 300, 270.0, and 9 on separate lines. discount has a default. The last call names the argument explicitly. *values collects positional arguments into a tuple. Similarly, **options can collect keyword arguments into a dictionary. Keep functions focused and prefer returned results when another part of the program needs the value.
Common mistakes
range(1, 5) stops at 4. A misplaced continue can skip the update needed to end a while loop. Do not use a mutable list as a default argument; Lesson 17 shows the safer None pattern.
Student tasks
1. Print the 7 times table from 7 x 1 through 7 x 10.
2. Add numbers from 1 through 100 with a loop. Expected sum: 5050.
3. Print numbers from 1 through 20, skipping multiples of 3 and stopping before 17.
4. Write rectangle_area(width, height). Verify that (4, 6) returns 24 and (0, 6) returns 0.
5. Use nested loops to print all row and column pairs for a 3 by 3 grid.
Completion check: submit examples of both loop types and a function that returns a value.