Learn Without Walls
← Back to Module 5

Module 5 Study Guide

Complete Review: Loops

Lesson 5.1: for Loops and range()

How for Loops Work

A for loop iterates over each item in a sequence, executing its body once per item.

# Loop over a list
colors = ["red", "green", "blue"]
for color in colors:
    print(color)

# Loop over a string
for char in "hello":
    print(char, end=" ")

range() with 1, 2, and 3 Arguments

range(5)          # 0, 1, 2, 3, 4
range(2, 7)       # 2, 3, 4, 5, 6
range(0, 10, 3)  # 0, 3, 6, 9
range(5, 0, -1)  # 5, 4, 3, 2, 1

Common Patterns

Lesson 5.2: while Loops

How while Loops Work

A while loop checks its condition before each iteration. It keeps running as long as the condition is True.

count = 1
while count <= 5:
    print(count)
    count += 1  # MUST update to avoid infinite loop

Key Use Cases

Avoiding infinite loops: Always ensure the loop condition will eventually become False. Common causes: forgetting to update the loop variable, updating in the wrong direction, or a condition that is always True.

Lesson 5.3: break, continue, and pass

Summary of Each Statement

# break - EXIT the loop entirely
for item in items:
    if item == target:
        break  # Stop the loop now

# continue - SKIP to the next iteration
for num in numbers:
    if num < 0:
        continue  # Skip negative numbers
    total += num

# pass - DO NOTHING (placeholder)
for item in items:
    if condition:
        pass  # TODO: implement later

Loop else Clause

A loop's else block runs only if the loop completed without hitting break. Useful for search patterns where you want to know if nothing was found.

for num in numbers:
    if num == target:
        print("Found!")
        break
else:
    print("Not found.")  # Runs if break was never triggered

Lesson 5.4: Nested Loops

How They Work

The inner loop completes all its iterations for each single iteration of the outer loop. If the outer runs n times and the inner runs m times, the total is n × m inner iterations.

# Print a grid pattern
for row in range(3):
    for col in range(4):
        print("* ", end="")
    print()  # New line after each row
* * * * * * * * * * * *

Key Points

for vs. while: Decision Guide

Ask yourself: "Do I know how many times this should repeat before the loop starts?"
Yes → Use for
No → Use while

Self-Check: Can You Do This?

Next Steps

With conditionals (Module 4) and loops (Module 5) mastered, you now have the core tools of programming logic. In Module 6: Lists, you will learn to store collections of data and combine them powerfully with the loops you have learned here.

Complete the Practice Problems | Take the Quiz