← All lessons

Lesson 04

Loops

A for loop repeats once for each item in a sequence. range(5) gives the numbers 0 through 4.

A while loop repeats as long as its condition stays True. Be careful: a condition that never becomes False loops forever.

Use break to exit a loop early and continue to skip to the next round.

for i in range(5):
    print(f"Counting: {i}")

total = 0
n = 1
while n <= 10:
    total += n
    n += 1
print(f"Sum of 1..10 is {total}")

Check your understanding

How many times does range(5) iterate?

CHALLENGE

Print the multiples of 3 from 1 through 10, each on its own line.

Practice →
Next: Functions →