Exerpad
🔥1
10 XP
Lv.1 Beginner
Log In

Looping with For

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

Repeat N Times

Use range(n) to repeat something n times:

python
for i in range(5):
print("Hello!")

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:

text
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:

text
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:

text
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)

For vs While

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