Chapter 9: Loops
Repeat computations efficiently in Python. Learn to generate number series using range(), repeat tasks with for and while loops, step across multi-dimensional spaces using nested loops, and control iteration flow with break, continue, and pass.
Why Do We Need Loops?
In programming, we often need to perform a task over and over again. Repeating the same code multiple times manually is inefficient, error-prone, and makes codebase maintenance difficult. Loops solve this by allowing us to execute a block of code repeatedly based on a sequence or a conditional check.
Before diving into loop constructs, let's explore Python's built-in helper for generating sequences: the range() function.
9.1 The range() Function
The range() function outputs an ordered sequence of numbers. It is lazy and does not explicitly generate list sequences in memory under Python 3 until iterated, which saves processing overhead.
range(n): Generates values from0up to, but not including,n. E.g.range(3)yields0, 1, 2.range(start, end): Generates values fromstartup to, but not including,end. E.g.range(10, 15)yields10, 11, 12, 13, 14.
Toggle parameter modes and slide parameters to inspect the generated values sequence.
Try running this code block to verify how Python outputs range boundaries:
# Printing ranges
print("Single limit range(3):", list(range(3)))
print("Double limit range(10, 15):", list(range(10, 15)))
9.2 For Loops
A for loop repeats a set block of code a set number of times. You can iterate through lists using their index offsets, or you can loop directly across list elements without indexing variables.
Simulate replacing color squares with white squares. Select a loop method and click Step Iteration to watch the loop state update.
Here is the index-based color mutation syntax alongside element loops and enumerate():
# List of color elements
squares = ["red", "yellow", "green", "purple", "blue"]
# Method 1: Index mutation loop
for i in range(5):
squares[i] = "white"
# Method 2: Iterate elements directly
for square in squares:
print(square)
# Method 3: Get both using enumerate()
for i, square in enumerate(squares):
print("Index:", i, "Element:", square)
9.2.2 Nested Loops
A nested loop is a loop inside another loop. The inner loop runs to completion (covering all its iterations) for each single step or increment of the outer loop. This is highly useful for scanning grids, tables, and multi-dimensional matrices.
Step through the grid loops. The outer loop index i handles grid rows, and the inner loop index j highlights columns within that row.
Here is the Python syntax used to print grid coordinates in row-by-row matrix form:
# Nested loops coordinate scan
for i in range(3): # Outer Row loop
for j in range(3): # Inner Column loop
print(f"Row {i}, Col {j}")
9.3 While Loops
A while loop executes a block of code repeatedly as long as a specified condition evaluates to True. Unlike for loops, you do not always know the exact number of iterations beforehand.
Copy elements from squares list into new_squares list, but stop early when a non-orange square is encountered.
This is the Python while loop logic implementation used in the simulator above:
# Copy orange squares until non-orange square is met
squares = ["orange", "orange", "purple", "orange"]
new_squares = []
i = 0
while i < len(squares) and squares[i] == "orange":
new_squares.append(squares[i])
i += 1
print("Copied elements:", new_squares)
9.4 Loop Control Statements (break, continue, pass)
Loop control statements change the default sequential iteration path of a loop:
break: Terminate the entire loop immediately.continue: Skip the rest of the current iteration block and skip directly to the next loop cycle.pass: Do nothing. Used as a syntax placeholder when Python requires a statement block but no action is needed.
Choose a statement rule to execute on item 3 as we iterate from 1 to 5. Observe how the instruction path and output values differ.
Try running this code block to verify how Python outputs loop control statements:
# Demonstrating control flow statements
print("Break demo (exits on 3):")
for val in [1, 2, 3, 4, 5]:
if val == 3:
break
print(" Value:", val)
print("\nContinue demo (skips 3):")
for val in [1, 2, 3, 4, 5]:
if val == 3:
continue
print(" Value:", val)
print("\nPass demo (placeholder):")
for val in [1, 2, 3, 4, 5]:
if val == 3:
pass # does nothing
print(" Value:", val)
Practice Quiz
Test your understanding of Python loops and control statements by answering the questions below.