What You Will Learn
Loops let you repeat code without writing it over and over. The for loop is the most common loop in Python.
Your First for Loop
for i in range(5):
print(i)
Expected output:
0
1
2
3
4
range(5) generates the numbers 0, 1, 2, 3, 4. The variable i takes each value in turn. The indented code runs once for each value.
range() Options
# range(stop) — 0 up to (but not including) stop
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# range(start, stop)
for i in range(2, 6):
print(i) # 2, 3, 4, 5
# range(start, stop, step)
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
# Counting down
for i in range(5, 0, -1):
print(i) # 5, 4, 3, 2, 1
Looping Over a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Expected output:
apple
banana
cherry
You will learn more about lists in a later lesson. For now, just know that a for loop can go through any collection of items.
Looping Over a String
word = "Python"
for letter in word:
print(letter)
Expected output:
P
y
t
h
o
n
Using the Loop Variable
for i in range(1, 6):
print(f"{i} x 3 = {i * 3}")
Expected output:
1 x 3 = 3
2 x 3 = 6
3 x 3 = 9
4 x 3 = 12
5 x 3 = 15
Accumulating a Result
A common pattern is to start with a value and build it up inside a loop:
total = 0
for i in range(1, 6):
total = total + i
print(f"Added {i}, total is now {total}")
print(f"Final total: {total}")
Expected output:
Added 1, total is now 1
Added 2, total is now 3
Added 3, total is now 6
Added 4, total is now 10
Added 5, total is now 15
Final total: 15
What You Learned
forloops repeat code for each item in a sequencerange()generates a sequence of numbers- You can loop over lists, strings, and other collections
- Use the loop variable to access each item
- Accumulate results by updating a variable inside the loop
In the next lesson, you will learn about while loops — loops that repeat as long as a condition is true.