For Loops

Week 1 — Python Basics Revision

Introduction

Imagine reading every name on a class roster one by one. That is what a for loop does — it repeats an action for each item in a sequence. For loops are one of the most used structures in all of programming.

How a For Loop Works

The loop picks one item at a time from a collection and runs the indented code block for each one.

fruits = ["Apple", "Banana", "Cherry"]

for fruit in fruits:
    print(fruit)
Output
Apple
Banana
Cherry

The variable fruit takes the value of each item in the list, one at a time. On the first pass it is "Apple", then "Banana", then "Cherry".

The range() Function

The range() function generates a sequence of numbers. It accepts up to three arguments: range(start, stop, step). The stop value is never included in the output.

# Count from 0 to 4
for i in range(5):
    print(i)

# Count from 1 to 5
for i in range(1, 6):
    print(i)

# Count by 2s: 0, 2, 4, 6, 8
for i in range(0, 10, 2):
    print(i)
Key point
range(5) produces 0, 1, 2, 3, 4 — five numbers starting from 0. The stop value (5) is not included.

Looping Through Strings

Strings are sequences too, so a for loop can visit each character.

word = "Python"
for letter in word:
    print(letter, end=" ")
# Output: P y t h o n
Output
P y t h o n

Using enumerate()

When you need the index and the value at the same time, use enumerate().

colors = ["Red", "Green", "Blue"]

for index, color in enumerate(colors):
    print(f"{index}: {color}")
Output
0: Red
1: Green
2: Blue

Looping Through Dictionaries

Use .items() to loop through both keys and values of a dictionary.

student = {"name": "Alice", "age": 22, "grade": "A"}

for key, value in student.items():
    print(f"{key}: {value}")
Output
name: Alice
age: 22
grade: A

Real-World Example

Processing a class of students to calculate the average score.

scores = [88, 92, 75, 95, 80]
total = 0

for score in scores:
    total += score

average = total / len(scores)
print(f"Class average: {average:.1f}")
Output
Class average: 86.0

How This Connects to OOP

In OOP, you will loop through collections of objects. Imagine a list of Student objects — a for loop lets you calculate the class average by visiting each student. Classes can even be made iterable with special methods like __iter__ and __next__.

Best Practices

  • Name loop variables meaningfully: for student in students: not for s in x:
  • Use enumerate() instead of tracking the index manually with a counter variable
  • Prefer for item in list: over for i in range(len(list)): when you do not need the index

Common Mistakes

  • Off-by-one errors: range(1, 10) goes up to 9, not 10
  • Modifying a list while looping through it — this causes skipped items or unexpected behavior
  • Using for i in range(len(list)): when direct iteration like for item in list: works perfectly

Practice Exercises

  1. Print the multiplication table for any number (1 to 10) using a for loop.
  2. Loop through a list of 5 names and print each with its position (use enumerate).
  3. Calculate the sum of all even numbers from 1 to 50 using range().

Summary

For loops handle known sequences beautifully. Next, we will learn while loops — for situations where you do not know how many times to repeat.