← All lessons
Programming basics · Lesson 4 of 9

Loops

A loop repeats a block of code. That's how a program prints a thousand receipts or checks every pixel in a photo without a thousand lines of code.

A while loop repeats as long as its condition is true. Something inside it has to change, or the condition stays true forever and the loop never ends.

n = 3
while n > 0:
    print(n)
    n = n - 1
print("Go!")
Prints
3
2
1
Go!

A for loop goes through the items of something one at a time. With range() it counts: range(5) gives 0, 1, 2, 3, 4. It starts at 0 and stops before 5, so it gives exactly five numbers. range(2, 6) gives 2 to 5, and a third number sets the step: range(0, 10, 3) gives 0, 3, 6, 9.

for i in range(1, 4):
    print(i * 10)
Prints
10
20
30

A common pattern keeps a running total: start a variable at 0 before the loop and add to it each time round. break leaves a loop straight away, and continue skips to the next time round.

total = 0
for i in range(1, 5):
    total = total + i
print(total)
Prints
10

Practice

How many lines does this print? (Type the number.)

for i in range(4):
    print("hi")
More info

Quick reference

while condition:Repeats while the condition is true.
for x in …:Runs once for each item.
range(stop)0 up to stop - 1. range(start, stop, step) for other counts.
break / continueLeave the loop now / skip to the next round.

The other computer science courses