01 / 21

Python
For Loops

Master iteration in Python: use for loops to traverse ranges, lists, and strings with confidence.

Python

What Is Iteration?

Iteration means repeating a block of code multiple times. Instead of writing the same instruction over and over, we tell the computer: "do this action for each item in a collection" or "do this action a certain number of times."

Without a Loop
Write print("Hello") five separate times: tedious and error-prone.
With a For Loop
Write one loop that calls print("Hello") five times automatically.

Anatomy of a For Loop

for item in sequence : keyword loop variable keyword iterable (data) colon # indented body (runs each iteration)

How a For Loop Executes

Start More items? in sequence Yes Assign next item to loop variable Run loop body No No End loop

The range() Function

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

range(n)
Produces integers from 0 up to (but not including) n.
range(a, b)
Produces integers from a up to (but not including) b.
range(a, b, s)
From a to b, stepping by s each time.

Iterating Over Lists

A list is one of Python's most versatile data structures. A for loop can walk through each element in order:

colors = ["red", "green", "blue"] for c in colors: print(c)
Output
red green blue

Iterating Over Strings

Strings are sequences of characters. A for loop visits each character one at a time:

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

for vs while

for loop while loop
Iteration type Definite (known count) Indefinite (condition-based)
Best for Sequences, ranges, collections Unknown end, user input
Risk of infinite loop Low Higher
Variable update Automatic (next item) Manual (must update yourself)
Syntax for x in seq: while cond:

Step-by-Step Approach

1
Identify the data. What are you iterating over: a range of numbers, a list, or a string?
2
Choose a meaningful variable name. Use descriptive names like num, name, or letter instead of single letters.
3
Write the header. for variable in sequence: followed by a colon.
4
Indent the body. Every line inside the loop must be indented by 4 spaces (or 1 tab).
5
Trace through mentally. Walk through the first 2-3 iterations to verify correctness before running.

Example 1: Summing with range()

Calculate the sum of integers from 1 to 5 using a for loop:

total = 0 for num in range(1, 6): total = total + num print("Sum:", total)
Output
Sum: 15

Example 2: Processing a List

Given a list of test scores, print whether each score is a pass (\( \geq 60 \)) or fail:

scores = [85, 42, 73, 58, 91] for score in scores: if score >= 60: print(score, "- Pass") else: print(score, "- Fail")
Output
85 - Pass 42 - Fail 73 - Pass 58 - Fail 91 - Pass

Example 3: Counting Vowels

Count the number of vowels in a string:

word = "education" count = 0 for letter in word: if letter in "aeiou": count = count + 1 print("Vowels:", count)
Output
Vowels: 5

Nested For Loops

You can place one for loop inside another. The inner loop runs completely for each iteration of the outer loop:

for row in range(1, 4): for col in range(1, 4): print(row * col, end=" ") print()
Output
1 2 3 2 4 6 3 6 9

range() with Step Values

0 1 2 3 4 5 6 7 8 9 +2 +2 +2 +2 range(0, 10, 2) Produces: 0, 2, 4, 6, 8 (10 is excluded)
for i in range(0, 10, 2): print(i, end=" ") # Output: 0 2 4 6 8

Common Mistakes

✕ Off-by-One Error
Using range(5) expecting 1-5, but getting 0-4. Remember: range starts at 0 and the stop value is excluded.
✕ Forgetting the Colon
Writing for x in range(5) without the colon at the end. Python requires a : after every loop header.
✕ Indentation Error
Not indenting the loop body. Python uses indentation (not braces) to define blocks. Mismatched indentation causes errors.

Iteration Summary

Iterable Type Syntax Example Loop Variable Gets
range() for i in range(5): Each integer: 0, 1, 2, 3, 4
List for x in [10, 20, 30]: Each element: 10, 20, 30
String for ch in "Hi": Each character: "H", "i"
range(a,b,s) for i in range(2,10,3): 2, 5, 8

Question 1 of 5

What does range(3) produce?

Question 2 of 5

How many times will this loop print?

for i in range(2, 8): print(i)

Question 3 of 5

What is the output of this code?

for ch in "abc": print(ch * 2, end=" ")

Question 4 of 5

What value of total will this code produce?

total = 0 for x in [3, 7, 1, 4]: total = total + x print(total)

Question 5 of 5

Which code correctly prints all even numbers from 2 to 10 (inclusive)?