Learn Without Walls
← Back to Module 5

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

SyntaxProducesDescription
range(n)0 to n-1n numbers starting from 0
range(a, b)a to b-1From 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

StatementEffectUse When
breakExits the loop immediatelyFound what you need; stop searching
continueSkips to next iterationSkip invalid/unwanted items
passDoes nothingPlaceholder 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 forUse while
Known number of iterationsUnknown number of iterations
Iterating over a collectionCondition-based repetition
Counting with range()Input validation
Processing each itemWaiting for a condition