Exerpad
🔥 1
10 XP
Lesson · Chapter: For Loops+10 XP for reading

Looping with For

The for loop is a simpler way to repeat things a specific number of times.

Prefer to watch? This chapter as a video:

Where you'll use this
Drawing rows of pixels, sending an invitation to every friend, printing a report per player — when you know how many rounds, for is the tool.

Repeat N Times

Use range(n) to repeat something n times:

python
for i in range(5):
print("Hello!")
Output
Press Run to see the output.

This prints Hello! five times. The variable i counts from 0 to 4.

range() with Start and Stop

range(start, stop) counts from start up to (but not including) stop:

python
for i in range(1, 6):
print(i)
Output
Press Run to see the output.

Output:

1
2
3
4
5

range() with Step

range(start, stop, step) lets you count by any amount:

python
for i in range(2, 11, 2):
print(i)
Output
Press Run to see the output.

Output:

2
4
6
8
10

Looping Over Strings

You can loop through each character in a string:

python
for letter in "Hello":
print(letter)
Output
Press Run to see the output.

Output:

H
e
l
l
o

Looping Over Lists

You can loop through items in a list:

python
colors = ["red", "blue", "green"]
for color in colors:
print(color)
Output
Press Run to see the output.

For vs While

Use for when you know how many times to loop. Use while when you don't know in advance.

Did you know?
A modern processor can run a few billion loop laps per second. The loop you just wrote finishes faster than your screen can even show one frame.

Check yourself

Pause & predict — what will this print?
for i in range(3):
    print(i)