Lesson 5.1: for Loops and range()
What You'll Learn
- What loops are and why they are essential
- How to write for loops to iterate over sequences
- How to use range() with 1, 2, and 3 arguments
- How to loop through strings and lists
- Common for loop patterns (accumulator, counting)
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!")
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}!")
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)
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)
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)
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=" ")
# Count backwards for i in range(5, 0, -1): print(i, end=" ")
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}")
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}")
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}")
# Start numbering from 1 for index, fruit in enumerate(fruits, start=1): print(f"{index}. {fruit}")
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}")
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}")
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
- for loops iterate over each item in a sequence
range(n)generates 0 through n-1range(start, stop)generates start through stop-1range(start, stop, step)allows counting by any increment- Common patterns: accumulator (running total), counting, string building
enumerate()gives you both index and value