Learn Without Walls
← Module 5 Home Lesson 1 of 4 Next Lesson →

Lesson 5.1: for Loops and range()

What You'll Learn

Why Do We Need Loops?

Imagine you want to print "Hello!" five times. Without loops, you would have to write the same line five times. With a loop, you write it once and tell Python how many times to repeat.

# Without a loop (tedious!)
print("Hello!")
print("Hello!")
print("Hello!")
print("Hello!")
print("Hello!")

# With a loop (much better!)
for i in range(5):
    print("Hello!")
Hello! Hello! Hello! Hello! Hello!
Loop: A programming structure that repeats a block of code multiple times. A for loop repeats for each item in a sequence (like a range of numbers or characters in a string).

The for Loop Syntax

A for loop has three parts: the for keyword, a loop variable, and an iterable (something to loop over).

for variable in iterable:
    # code to repeat (indented)
# Loop through a list of names
names = ["Alice", "Bob", "Charlie"]

for name in names:
    print(f"Hello, {name}!")
Hello, Alice! Hello, Bob! Hello, Charlie!

Each time through the loop, the variable name takes on the next value from the list. After the last item, the loop ends and Python continues with the code after the loop.

# Loop through a string (character by character)
word = "Python"

for letter in word:
    print(letter)
P y t h o n

The range() Function

range() generates a sequence of numbers. It is the most common way to control how many times a for loop runs.

range() with 1 argument: range(stop)

Generates numbers from 0 up to (but not including) stop.

for i in range(5):
    print(i)
0 1 2 3 4

range() with 2 arguments: range(start, stop)

Generates numbers from start up to (but not including) stop.

for i in range(1, 6):
    print(i)
1 2 3 4 5

range() with 3 arguments: range(start, stop, step)

Generates numbers from start to stop, incrementing by step.

# Count by 2s
for i in range(0, 11, 2):
    print(i, end=" ")
0 2 4 6 8 10
# Count backwards
for i in range(5, 0, -1):
    print(i, end=" ")
5 4 3 2 1
Remember: range() never includes the stop value. range(1, 5) gives you 1, 2, 3, 4 — not 5. This matches how Python indexing works (starting from 0).

Common for Loop Patterns

Pattern 1: Accumulator (Running Total)

# Sum numbers from 1 to 10
total = 0

for num in range(1, 11):
    total += num

print(f"Sum of 1 to 10: {total}")
Sum of 1 to 10: 55

Pattern 2: Counting

# Count vowels in a word
word = "programming"
vowel_count = 0

for letter in word:
    if letter in "aeiou":
        vowel_count += 1

print(f"Vowels in '{word}': {vowel_count}")
Vowels in 'programming': 3

Pattern 3: Building a String

# Build a string of stars
stars = ""

for i in range(5):
    stars += "* "

print(stars)
* * * * *

Looping with Index and Value

Sometimes you need both the index (position) and the value. Python provides the enumerate() function for this.

fruits = ["apple", "banana", "cherry"]

for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")
0: apple 1: banana 2: cherry
# Start numbering from 1
for index, fruit in enumerate(fruits, start=1):
    print(f"{index}. {fruit}")
1. apple 2. banana 3. cherry

Practical Examples

Example: Average Calculator

scores = [85, 92, 78, 95, 88]
total = 0

for score in scores:
    total += score

average = total / len(scores)
print(f"Average score: {average}")
Average score: 87.6

Example: Multiplication Table

number = 7

print(f"Multiplication table for {number}:")
for i in range(1, 11):
    result = number * i
    print(f"{number} x {i} = {result}")
Multiplication table for 7: 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

Try It Yourself!

Write a for loop that calculates the factorial of 6 (6! = 6 * 5 * 4 * 3 * 2 * 1 = 720).

Hint: Start with result = 1 and multiply by each number in range(1, 7).

Check Your Understanding

What will this code print?

total = 0
for i in range(1, 4):
    total += i * 2
print(total)

Answer: 12

Loop runs with i = 1, 2, 3. Each iteration: total += i * 2.
i=1: total = 0 + 2 = 2
i=2: total = 2 + 4 = 6
i=3: total = 6 + 6 = 12

Key Takeaways

← Module 5 Home Lesson 1 of 4 Next: while Loops →