Python Loops & Iteration

Complete guide to Python loops: for, while, break, continue, range, enumerate, and zip.

For Loop

# Loop through list
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
    print(fruit)

# Loop through string
for char in 'Python':
    print(char)  # P, y, t, h, o, n

# Loop through dictionary
scores = {'alice': 90, 'bob': 85}
for name, score in scores.items():
    print(f"{name}: {score}")

While Loop

# Basic while loop
count = 0
while count < 5:
    print(count)
    count += 1  # prints 0, 1, 2, 3, 4

# While with condition
password = ''
while password != 'secret':
    password = input('Enter password: ')

# Infinite loop (use Ctrl+C to stop)
while True:
    response = input('Enter quit to exit: ')
    if response == 'quit':
        break

Break & Continue

# Break - exit loop
for i in range(10):
    if i == 5:
        break  # stops at 5
    print(i)  # prints 0, 1, 2, 3, 4

# Continue - skip iteration
for i in range(5):
    if i == 2:
        continue  # skips 2
    print(i)  # prints 0, 1, 3, 4

# Pass - do nothing (placeholder)
for i in range(3):
    pass  # empty loop body

Range Function

# range(stop)
for i in range(5):
    print(i)  # 0, 1, 2, 3, 4

# range(start, stop)
for i in range(2, 7):
    print(i)  # 2, 3, 4, 5, 6

# range(start, stop, step)
for i in range(0, 10, 2):
    print(i)  # 0, 2, 4, 6, 8

# Reverse range
for i in range(5, 0, -1):
    print(i)  # 5, 4, 3, 2, 1

Enumerate

# Get index and value
fruits = ['apple', 'banana', 'orange']
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")
# 0: apple
# 1: banana
# 2: orange

# Start from custom index
for i, fruit in enumerate(fruits, start=1):
    print(f"{i}. {fruit}")
# 1. apple
# 2. banana
# 3. orange

Zip Function

# Combine two lists
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
    print(f"{name} is {age} years old")

# Zip three lists
subjects = ['Python', 'Java', 'C++']
scores = [95, 88, 92]
for name, subj, score in zip(names, subjects, scores):
    print(f"{name}: {subj} = {score}")

# Create dictionary from two lists
keys = ['a', 'b', 'c']
values = [1, 2, 3]
d = dict(zip(keys, values))  # {'a': 1, 'b': 2, 'c': 3}

Nested Loops

# 2D grid
for i in range(3):
    for j in range(3):
        print(f'({i}, {j})', end=' ')
    print()  # new line

# Loop through matrix
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
for row in matrix:
    for item in row:
        print(item, end=' ')

Loop Else

# For-else (runs if no break)
for i in range(5):
    print(i)
else:
    print('Loop completed')  # runs

# With break (else does NOT run)
for i in range(5):
    if i == 3:
        break
    print(i)
else:
    print('Loop completed')  # does NOT run

# While-else
count = 0
while count < 3:
    print(count)
    count += 1
else:
    print('Done')  # runs after loop