Module 5 Quick Reference
Loops Cheat Sheet
for Loop
# Loop over a sequence for item in sequence: # do something with item # Loop with range for i in range(5): # 0, 1, 2, 3, 4 for i in range(2, 8): # 2, 3, 4, 5, 6, 7 for i in range(0, 10, 2): # 0, 2, 4, 6, 8 for i in range(5, 0, -1): # 5, 4, 3, 2, 1 # Loop with index and value for index, value in enumerate(items): print(index, value)
range() Function
| Syntax | Produces | Description |
|---|---|---|
range(n) | 0 to n-1 | n numbers starting from 0 |
range(a, b) | a to b-1 | From a up to (not including) b |
range(a, b, s) | a, a+s, a+2s, ... | From a to b-1, stepping by s |
Remember: The stop value is never included!
while Loop
# Basic while loop while condition: # code to repeat # MUST update condition to avoid infinite loop! # Common pattern: input validation while True: value = input("Enter a positive number: ") if value.isdigit() and int(value) > 0: break print("Invalid! Try again.")
Loop Control Statements
| Statement | Effect | Use When |
|---|---|---|
break | Exits the loop immediately | Found what you need; stop searching |
continue | Skips to next iteration | Skip invalid/unwanted items |
pass | Does nothing | Placeholder for future code |
Nested Loops
# Nested loop: inner runs fully for each outer iteration for i in range(3): # Outer: 3 times for j in range(4): # Inner: 4 times each = 12 total print("*", end=" ") print() # New line after each row
Total iterations: outer × inner (e.g., 3 × 4 = 12)
Common Patterns
# Accumulator (running total) total = 0 for num in numbers: total += num # Counting count = 0 for item in items: if condition: count += 1 # Finding max/min max_val = numbers[0] for num in numbers: if num > max_val: max_val = num # Building a string result = "" for char in text: result += char.upper()
for vs. while
| Use for | Use while |
|---|---|
| Known number of iterations | Unknown number of iterations |
| Iterating over a collection | Condition-based repetition |
| Counting with range() | Input validation |
| Processing each item | Waiting for a condition |