Table of Contents
Understanding `for` Loops
A for loop lets you repeat some code for each item in a sequence (like a list, string, or range of numbers). Instead of manually counting or copying lines, Python does the repetition for you.
Basic structure:
for variable in sequence:
# code that uses variablevariableis a name you choose; it represents each item one by one.sequenceis something you can go through item by item (likerange(5), a list, or a string).- The indented block is what runs on every loop.
Example:
for i in range(5):
print("Loop number:", i)This prints:
Loop number: 0
Loop number: 1
Loop number: 2
Loop number: 3
Loop number: 4
Notice that range(5) goes from 0 up to 4, not including 5.
`range()` with `for` Loops
range() is commonly used with for loops to repeat something a certain number of times or to generate a series of numbers.
One argument: `range(stop)`
for i in range(3):
print(i)Output:
0
1
2
Here stop = 3, and Python counts from 0 up to 2.
Two arguments: `range(start, stop)`
for i in range(2, 5):
print(i)Output:
2
3
4
Now counting starts at 2 and stops before 5.
Three arguments: `range(start, stop, step)`
step is how much you add each time.
for i in range(0, 10, 2):
print(i)Output:
0
2
4
6
8You can also count backwards with a negative step:
for i in range(5, 0, -1):
print(i)Output:
5
4
3
2
1Looping Over Different Types of Sequences
A for loop is not just for numbers. It works with any iterable object (things you can go through item by item). As a beginner, you’ll mostly use:
- Strings
- Lists
- Other collection types when you learn them
Looping over a string
Each loop gives you the next character:
text = "Python"
for ch in text:
print(ch)Output:
P
y
t
h
o
nYou can use this to count characters or search in text:
text = "banana"
count_a = 0
for ch in text:
if ch == "a":
count_a += 1
print("Number of 'a':", count_a)Looping over a list
Suppose you have a list of numbers:
numbers = [10, 20, 30]
for n in numbers:
print("Number:", n)Or a list of strings:
names = ["Alice", "Bob", "Charlie"]
for name in names:
print("Hello,", name)Using the Loop Variable
Inside the loop, the loop variable is just a normal variable that changes each time.
Example: multiply each number by 2:
numbers = [1, 2, 3, 4]
for n in numbers:
doubled = n * 2
print(n, "doubled is", doubled)You can give the variable a name that makes sense for what it represents:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("I like", fruit)Good naming makes loops easier to understand.
`for` Loops with `range()` vs. Direct Iteration
There are two common styles:
- Loop directly over items
- Loop over indexes (positions)
1. Loop directly over items
This is the most common and usually the clearest:
colors = ["red", "green", "blue"]
for color in colors:
print(color)2. Loop over indexes with `range(len(...))`
Sometimes you need the position (index) as well as the value:
colors = ["red", "green", "blue"]
for i in range(len(colors)):
print("Index", i, "has color", colors[i])Here:
len(colors)gives the number of items.range(len(colors))gives indexes from0tolen(colors) - 1.
Using `for` Loops to Build New Data
You can use for loops to create new lists or build up strings.
Building a list
Example: squares of numbers from 1 to 5:
squares = []
for n in range(1, 6):
squares.append(n * 2)
# or squares.append(n * n)
print(squares)Output:
[2, 4, 6, 8, 10]Building a string
Example: add ! after each character:
text = "hi"
result = ""
for ch in text:
result = result + ch + "!"
print(result)Output:
h!i!Nested `for` Loops (Loop Inside a Loop)
You can put a for loop inside another for loop to handle combinations of things.
Example: simple multiplication table:
for i in range(1, 4): # outer loop
for j in range(1, 4): # inner loop
print(i, "x", j, "=", i * j)
print("----")Output:
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
----
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
----
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
----The inner loop runs completely for each value of the outer loop.
Common Patterns with `for` Loops
These patterns show up often when using for loops.
Summing values
Add up numbers:
numbers = [5, 8, 3]
total = 0
for n in numbers:
total = total + n
print("Total:", total)Finding a maximum
Find the largest number manually:
numbers = [10, 4, 7, 20, 3]
max_value = numbers[0]
for n in numbers:
if n > max_value:
max_value = n
print("Max:", max_value)Counting with a condition
Count how many items match a rule:
numbers = [1, 2, 3, 4, 5, 6]
even_count = 0
for n in numbers:
if n % 2 == 0:
even_count += 1
print("Even numbers:", even_count)Using `for` with `break` and `continue`
The general ideas of break and continue are part of loops in general, but here are quick examples specifically with for loops.
`break` in a `for` loop
Stop the loop early when a condition is met:
numbers = [3, 7, 2, 9, 5]
for n in numbers:
if n == 9:
print("Found 9!")
break
print("Checking:", n)Output:
Checking: 3
Checking: 7
Checking: 2
Found 9!
After break, the loop ends completely.
`continue` in a `for` loop
Skip the rest of the current loop and go on to the next item:
for n in range(1, 6):
if n == 3:
continue # skip printing 3
print(n)Output:
1
2
4
5Typical Beginner Mistakes with `for` Loops
Here are a few errors you might run into and how to fix them.
1. Forgetting the colon
Wrong:
for i in range(5)
print(i)Correct:
for i in range(5):
print(i)2. Wrong indentation
Wrong:
for i in range(3):
print(i)Python will give an indentation error. Indent the loop body:
for i in range(3):
print(i)3. Using the wrong `range` values
Expecting 1 to 5 but writing:
for i in range(5):
print(i)
This prints 0 to 4. To get 1 to 5, use:
for i in range(1, 6):
print(i)4. Modifying the list while looping over it
This can lead to surprising results. Example:
numbers = [1, 2, 3, 4]
for n in numbers:
if n % 2 == 0:
numbers.remove(n) # modifying while loopingBetter: build a new list or use other techniques once you know them. For now, avoid changing the list you are looping over unless you understand the effects.
Practice Ideas for `for` Loops
Here are a few small tasks to try on your own:
- Print numbers from 1 to 10.
- Print all even numbers from 2 to 20.
- Given a string, print each character on a separate line.
- Given a list of names, print
"Hello, <name>"for each. - Ask the user for a number
nand print the squares from1^2up to $n^2$. - Count how many times a chosen letter appears in a word.
Use for loops with strings, lists, and range() to solve them.