Decisions & Loops Lesson 13 of 23
Python for Loops and range()
Loop through lists, strings and ranges with for, use range() with start, stop and step, enumerate() for numbering, and nested loops for tables and patterns.
The for loop is Python's most-used loop. It goes through a collection, such as a list, a string or a range of numbers, one item at a time.
Looping through a list
subjects = ["Math", "Science", "English", "Filipino"]
for subject in subjects:
print("Study", subject)
Output
Study Math Study Science Study English Study Filipino
Read it like English: "for each subject in subjects, print…". The variable subject takes each value in turn.
Looping through a string
for letter in "Luzon":
print(letter, end=" ")
Output
L u z o n
range(): looping a number of times
| Code | Numbers produced |
|---|---|
range(5) | 0, 1, 2, 3, 4 |
range(1, 6) | 1, 2, 3, 4, 5 |
range(0, 21, 5) | 0, 5, 10, 15, 20 |
range(10, 0, -1) | 10, 9, 8 … 1 |
The stop number is never included. range(1, 6) stops at 5.
n = 7
for i in range(1, 11):
print(f"{n} x {i} = {n * i}")
Output
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70
Totals and counts
grades = [88, 72, 95, 60, 81]
total = 0
passed = 0
for g in grades:
total += g
if g >= 75:
passed += 1
print("Average:", total / len(grades))
print("Passed:", passed, "of", len(grades))
Output
Average: 79.2 Passed: 3 of 5
enumerate(): getting the position too
top = ["Maria", "Jose", "Gabriela"]
for rank, name in enumerate(top, start=1):
print(f"{rank}. {name}")
Output
1. Maria 2. Jose 3. Gabriela
zip(): two lists together
names = ["Ana", "Ben", "Carla"]
scores = [92, 85, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}")
Output
Ana: 92 Ben: 85 Carla: 78
break and continue
They work like in while loops:
stock = {"Pandesal": 40, "Chips": 0, "Kape": 200}
for item in ["Pandesal", "Chips", "Kape"]:
if stock[item] == 0:
print(item, "- out of stock, skipping")
continue
print(item, "- available")
Output
Pandesal - available Chips - out of stock, skipping Kape - available
Nested loops
for row in range(1, 5):
for col in range(row):
print("*", end="")
print()
Output
* ** *** ****
The inner loop runs completely for each round of the outer loop. Nested loops are used for tables, grids, seat plans and patterns, a favorite in programming exams.
for…else
Like while, a for loop can have an else that runs if the loop finished without break. It's perfect for searching:
n = 29
for d in range(2, n):
if n % d == 0:
print(n, "is not prime, divisible by", d)
break
else:
print(n, "is prime!")
Output
29 is prime!
The loop variable is optional
If you just want to repeat something and don't need the number, use _:
for _ in range(3):
print("Hip hip hooray!")
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04