All coding lessonsLesson 5 of 10

Loops: for and while

Repeating work without repeating yourself

A loop repeats a block of code. Python has two: for, which walks through the items of a sequence, and while, which repeats as long as a condition stays true.

The for loop

for fruit in ["apple", "pear", "plum"]:
    print(fruit.upper())

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

for i in range(2, 11, 2): # 2,4,6,8,10
    print(i)

range(stop), range(start, stop) and range(start, stop, step) generate numbers lazily — the stop value is never included.

enumerate and zip

names = ["Ada", "Alan", "Grace"]
for index, name in enumerate(names, start=1):
    print(index, name)

ages = [36, 41, 45]
for name, age in zip(names, ages):
    print(f"{name} is {age}")

The while loop

total = 0
n = 1
while total < 100:
    total += n
    n += 1
print(n, total)

Every while loop must change something that eventually makes the condition false, otherwise it runs forever. That is the classic infinite loop.

break, continue and loop else

for n in range(2, 20):
    for d in range(2, n):
        if n % d == 0:
            break        # leave the inner loop
    else:
        print(n, "is prime")  # runs when no break happened

for n in range(10):
    if n % 2:
        continue          # skip to the next iteration
    print(n)

Accumulator pattern

numbers = [4, 8, 15, 16, 23, 42]
total = 0
for n in numbers:
    total += n
print(total / len(numbers))  # the mean
Ask Teacher Smith questions about this Python lessonOpens your AI tutor with a question about “Loops: for and while” →