exercises / cycles
exercise · 01
v0.1.0

Cycles

for · while · loops

Lesson · 1 of 4

A loop is how a program does the same thing many times — once per item, or as long as a condition holds. They're the engine behind almost every piece of software: walking a list, polling a sensor, drawing every frame.

01 The for loop

Iterates over any sequence — a list, a string, a range, the keys of a dict, the lines of a file.

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

Each iteration i is bound to the next item from the sequence. When the sequence runs out, the loop ends.

for ch in "hi":
    print(ch)
# h
# i
for x in [10, 20, 30]:
    print(x * 2)
# 20 40 60

02 range() — generating numbers

The most common companion to for. Three forms — each is half-open: start included, stop excluded.

range(stop)0, 1, … stop−1 range(start, stop)start, start+1, … stop−1 range(start, stop, step)arithmetic progression, step can be negative
list(range(5))           # [0, 1, 2, 3, 4]
list(range(2, 10, 3))    # [2, 5, 8]
list(range(5, 0, -1))    # [5, 4, 3, 2, 1]

03 enumerate & zip

Need the index along with the item? Reach for enumerate. Iterating two sequences in lockstep? zip.

for i, ch in enumerate("abc"):
    print(i, ch)
# 0 a
# 1 b
# 2 c
names = ["a", "b"]
ages  = [10, 20]
for n, a in zip(names, ages):
    print(n, a)

04 The while loop

Repeats as long as a condition is true. Use it when you don't know in advance how many iterations you'll need.

x = 10
while x > 0:
    x -= 3
print(x)  # -2

Forget to make progress toward the exit condition and you've made an infinite loop — fine for servers, fatal for anything else. Always make sure something inside the body changes the condition.

05 break & continue

break leaves the nearest enclosing loop immediately. continue skips the rest of the current iteration and jumps back to the condition.

for n in range(10):
    if n == 4:
        break
    print(n)
# 0 1 2 3
for n in range(5):
    if n % 2 == 0:
        continue
    print(n)
# 1 3

06 The else on a loop

A surprising feature: else on a for or while runs only if the loop wasn't broken out of. Perfect for "didn't find it" logic.

for n in [2, 4, 7, 8]:
    if n % 2:
        print("odd:", n)
        break
else:
    print("all even")
# odd: 7

07 Nested loops

Loops inside loops. The inner loop runs fully for each step of the outer.

for i in range(1, 4):
    for j in range(1, 4):
        print(i * j, end=" ")
    print()
# 1 2 3
# 2 4 6
# 3 6 9

08 Infinite cycles — itertools.cycle

For when you genuinely want a repeating, infinite stream of values. Pair it with islice to take only what you need.

from itertools import cycle, islice
list(islice(cycle("AB"), 5))
# ['A', 'B', 'A', 'B', 'A']

Worked examples · 2 of 4

Watch how it's done

Four small problems with their thinking shown step by step. Try to predict each solution before revealing it — that's where the learning happens.

01 Sum the numbers 1 to 100 accumulator

Compute the sum of all integers from 1 to 100, inclusive. Print the result.

Approach

Use the accumulator pattern: start with a running total of 0, walk through every value from 1 up to 100, and add each one to the total.

Remember range is half-open — to include 100, you need range(1, 101).

Solution
total = 0
for i in range(1, 101):
    total += i
print(total)
Output5050
02 Print 7's multiplication table simple for

Print the 7 times table, lines like "7 × 1 = 7" up through "7 × 10 = 70".

Approach

Loop i over the values 1 to 10. On each pass, print the formula and the result. Use an f-string for a clean format.

Solution
for i in range(1, 11):
    print(f"7 × {i} = {7 * i}")
Output7 × 1 = 7 7 × 2 = 14 7 × 3 = 21 … 7 × 10 = 70
03 FizzBuzz (1 to 15) conditional

Walk the numbers 1 to 15. Print Fizz when divisible by 3, Buzz when divisible by 5, FizzBuzz when divisible by both, otherwise the number itself.

Approach

Check the most specific case first (divisible by 15) — otherwise the first match wins and you'd print "Fizz" for 15.

Use the modulo operator %: it returns the remainder. n % 3 == 0 means "n is divisible by 3".

Solution
for n in range(1, 16):
    if n % 15 == 0:
        print("FizzBuzz")
    elif n % 3 == 0:
        print("Fizz")
    elif n % 5 == 0:
        print("Buzz")
    else:
        print(n)
Output1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
04 Find the first negative break / for-else

In the list [4, 7, 2, -3, 8, -1], print the first negative number you find. If there isn't one, print "no negatives".

Approach

Loop through the list. The moment you spot a negative, break out — there's no reason to keep checking.

Use the loop's else clause to handle the "ran to the end without finding anything" case. It only runs if you didn't break.

Solution
nums = [4, 7, 2, -3, 8, -1]
for n in nums:
    if n < 0:
        print("found:", n)
        break
else:
    print("no negatives")
Outputfound: -3
1 / 7
Practice
1 / 10
0%
A

Nicely done.

0correct
0%score
0:00time
Back to catalog