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
- Accumulator:
total = 0; for x in data: total += x - Counter:
count = 0; for x in data: if condition: count += 1 - enumerate(): Get both index and value:
for i, val in enumerate(list):
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
- Input validation: Keep asking until valid input is given
- Sentinel values: Loop until a special "stop" value is entered
- Unknown iterations: When you cannot predict how many times to loop
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
- Use different variable names for outer and inner loops (e.g.,
iandj) - The
print()after the inner loop creates row breaks - Trace through small examples to understand the execution order
- Be aware of performance: nested loops multiply iterations
for vs. while: Decision Guide
Yes → Use
for
No → Use
while
Self-Check: Can You Do This?
- Write a for loop that prints numbers 1 to 20
- Use range() with 1, 2, and 3 arguments correctly
- Calculate a sum using the accumulator pattern
- Write a while loop for input validation
- Explain when to use for vs. while
- Use break to exit a loop early when searching
- Use continue to skip specific items
- Explain what pass does and when to use it
- Write nested loops to create a pattern or table
- Calculate total iterations in nested loops
- Trace through loop code and predict the output
- Avoid and fix infinite loops
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.