Theory

Loops repeat code multiple times.

FOR loop - for a specific number of times:

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

range(5) gives numbers from 0 to 4.
range(1, 6) gives numbers from 1 to 5.

WHILE loop - while condition is true:

count = 0
while count < 3:
print(count)
count = count + 1 # or count += 1

Exercises in this lesson

1

Loop Repeats the Line

A for loop repeats the lines that are indented under it. range(3) means "three times". The code below shows Hi three times. Change the text so the program…

Easy Points: 5
2

Range Starts at One

range(3) counts from 0: it gives 0, 1, 2. To choose where to start and where to stop, give range two numbers: range(start, stop). It stops BEFORE stop, so…

Easy Points: 5
5

Sum Numbers

Calculate the sum of numbers from 1 to 10 using a loop. Store result in 'total' and print it. Expected result: 55

Medium Points: 20
6

While Counts to Three

A while loop repeats while its condition is true. Here the last line is unfinished: the counter n must grow by 1 on every pass, otherwise the loop would never…

Easy Points: 5
Solve in the playground

Frequently asked questions

What is the lesson “Loops” about?

Learn to repeat actions using loops.

How many exercises are in this lesson?

This lesson has 7 exercises.

Do I need to install anything to do the exercises?

No. The code is written and run in the browser.

Next lesson: Lists →