Loops: Repeating Without Retyping

Python for Absolute Beginners · Lesson 10

What you’ll learn

1 / 15

Why loops exist

2 / 15

Without a loop: five lines for 1 to 5

print(1)
print(2)
print(3)
print(4)
print(5)

Output:
1
2
3
4
5

That works, but it does not scale.

3 / 15

For loops and range()

4 / 15

A for loop with range()

for number in range(5):
    print(number)

Output:
0
1
2
3
4

That zero start surprises everyone once, then becomes habit.

5 / 15

Range with a start and stop

for number in range(1, 6):
    print(number)

Output:
1
2
3
4
5

The stop value is always one past the last number you get.

6 / 15

A loop through a string

for letter in "cat":
    print(letter)

Output:
c
a
t

Same shape: “for each thing in this sequence, do the indented block” — here the sequence is characters.

7 / 15

While loops: repeat until something changes

8 / 15

A while loop in code

count = 1
while count <= 5:
    print(count)
    count = count + 1

Output:
1
2
3
4
5

When count reaches 6, the condition is false and the loop stops.

9 / 15

The one loop mistake every beginner makes

10 / 15

An infinite loop (do not run this as-is)

count = 1
while count <= 5:
    print(count)

This prints 1 forever, because count never changes.

11 / 15

Hands-on exercise

12 / 15

Key takeaways

13 / 15

Take the quiz

Take the Lesson 10 quiz — 5 quick questions to check what you learned.

14 / 15

Next lesson

Drawing with Turtle

15 / 15

Press play on any slide and the lesson plays on by itself from there. You can still click Next or click a slide to move on.