7.2. for loops
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.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Chapter 1: What Is Programming?
- ☰ 1.1. What is a computer program?
- ☰ 1.2. What is Python?
- ☰ 1.3. Where is Python used?
- ☰ 1.4. How programming helps solve problems
- ☰ 1.5. Your first Python program
-
- ☰ 2. Chapter 2: Setting Up Python
- ☰ 2.1. Installing Python (Windows / macOS / Linux)
- ☰ 2.2. Using Python in the terminal
- ☰ 2.3. Using an IDE (IDLE / VS Code)
- ☰ 2.4. Running Python scripts
- ☰ 2.5. Python interactive mode
-
- ☰ 3. Chapter 3: Variables and Data Types
- ☰ 3.1. What is a variable?
- ☰ 3.2. Creating variables
- ☰ 3.3. Numbers
- ☰ 3.4. Test
- ☰ 3.5. Boolean values
- ☰ 3.6. Type checking
-
- ☰ 4. Chapter 4: Basic Operations
- ☰ 4.1. Arithmetic operations
- ☰ 4.2. Working with numbers
- ☰ 4.3. String operations
- ☰ 4.4. Combining text and variables
- ☰ 4.5. Comments in Python
-
- ☰ 5. Chapter 5: User Input and Output
- ☰ 5.1. Getting input from the user
- ☰ 5.2. Converting input to numbers
- ☰ 5.3. Formatting output
- ☰ 5.4. Writing interactive programs
-
- ☰ 6. Chapter 6: Conditions
- ☰ 6.1. Comparison operators
- ☰ 6.2. Logical operators
- ☰ 6.3. if, elif, else
- ☰ 6.4. Nested conditions
- ☰ 6.5. Common beginner mistakes
-
- ☰ 7. Chapter 7: Loops
- ☰ 7.1. Why loops are useful
- ☰ 7.2. for loops
- ☰ 7.3. while loops
- ☰ 7.4. Loop counters
- ☰ 7.5. break and continue
- ☰ 7.6. Loop exercises
-
- ☰ 8. Chapter 8: Data Collections
- ☰ 8.1. Lists
- ☰ 8.2. Tuples
- ☰ 8.3. Dictionaries
- ☰ 8.4. Sets (basics)
- ☰ 8.5. Choosing the right data structure
-
- ☰ 9. Chapter 9: Functions
- ☰ 9.1. Why functions matter
- ☰ 9.2. Defining functions
- ☰ 9.3. Parameters and arguments
- ☰ 9.4. Return values
- ☰ 9.5. Scope (local vs global)
- ☰ 9.6. Reusing code
-
- ☰ 10. Chapter 10: Working with Files
- ☰ 10.1. What is a file?
- ☰ 10.2. Reading text files
- ☰ 10.3. Writing and appending files
- ☰ 10.4. File paths
- ☰ 10.5. Simple file-based programs
-
- ☰ 11. Chapter 11: Errors and Debugging
- ☰ 11.1. Types of errors
- ☰ 11.2. Reading error messages
- ☰ 11.3. Common beginner errors
- ☰ 11.4. try and except
- ☰ 11.5. Debugging strategies
-
- ☰ 12. Chapter 12: Using Python Libraries
- ☰ 12.1. What is a library?
- ☰ 12.2. Importing modules
- ☰ 12.3. Standard libraries
- ☰ 12.3.1. math
- ☰ 12.3.2. random
- ☰ 12.3.3. datetime
-
- ☰ 12.4. Installing external libraries with pip
-
- ☰ 13. Chapter 13: Object-Oriented Programming
- ☰ 13.1. What is object-oriented programming?
- ☰ 13.2. Classes and objects
- ☰ 13.3. The `__init__` method
- ☰ 13.4. Attributes and methods
- ☰ 13.5. Encapsulation
- ☰ 13.6. Inheritance (basics)
- ☰ 13.7. Simple OOP examples
-
- ☰ 14. Chapter 14: Automation with Python
- ☰ 14.1. What is automation?
- ☰ 14.2. Automating simple tasks
- ☰ 14.3. Working with files and folders
- ☰ 14.4. Automating text processing
- ☰ 14.5. Scheduling scripts
- ☰ 14.6. Practical automation examples
-
- ☰ 15. Chapter 15: Web Development with Python
- ☰ 15.1. How the web works (basic overview)
- ☰ 15.2. Introduction to Flask
- ☰ 15.3. Creating a simple web server
- ☰ 15.4. Routing and templates
- ☰ 15.5. Handling user input (forms)
- ☰ 15.6. Very basic APIs
-
- ☰ 16. Chapter 16: Data Science with Python
- ☰ 16.1. What is data science?
- ☰ 16.2. Working with data
- ☰ 16.3. Introduction to NumPy
- ☰ 16.4. Introduction to pandas
- ☰ 16.5. Data visualization with matplotlib
- ☰ 16.6. Simple data analysis examples
-
- ☰ 17. Chapter 17: Mini Projects
- ☰ 17.1. Number guessing game
- ☰ 17.2. Simple calculator
- ☰ 17.3. To-do list
- ☰ 17.4. Password generator
- ☰ 17.5. Quiz application
- ☰ 17.6. Small web or data project
-
- ☰ 18. Chapter 18: Next Steps
- ☰ 18.1. How to practice Python
- ☰ 18.2. Writing clean and readable code
- ☰ 18.3. Choosing a specialization
- ☰ 18.3.1. Web development
- ☰ 18.3.2. Data science
- ☰ 18.3.3. Automation
- ☰ 18.3.4. Software development
-
- ☰ 18.4. Learning resources and communities
-
- ☰ 19. Appendix
- ☰ 19.1. Python syntax cheat sheet
- ☰ 19.2. Common errors and solutions
- ☰ 19.3. Glossary of terms
-
Comments
Please login to add a comment.
Don't have an account? Register now!