Python for Loops
Learn how to repeat instructions efficiently using Python's
for loop. You will learn how to iterate through
lists, strings, tuples, sets, dictionaries and ranges, while
building practical programs that process data automatically.
What You Will Learn
- Understand why loops are important in programming.
- Write and understand Python
forloops. - Iterate through different Python collections.
- Use
range()to generate sequences of numbers. - Combine loops with conditions.
- Build nested loops for more complex problems.
- Understand Python's
for...elsestructure. - Apply loops to practical programming problems.
What Is a Loop?
A loop is a programming structure that allows us to execute a block of code repeatedly.
Imagine that you need to print the numbers from 1 to 100.
Without a loop, you would have to write 100 separate
print() statements.
With a loop, the same task can be completed using only a few lines of code.
print(1)
print(2)
print(3)
print(4)
print(5)
for number in range(1, 6):
print(number)
1 2 3 4 5
Loops allow a program to perform repetitive work automatically instead of repeating code manually.
Why Loops Matter
Loops are one of the most important concepts in programming. Real applications constantly process collections of data.
For example, a program may need to:
- Process thousands of customer records.
- Calculate student marks.
- Display products from a database.
- Search through a list of names.
- Calculate totals and averages.
- Generate reports.
- Process files or API responses.
Instead of writing the same instruction repeatedly, we write the instruction once and let the loop handle repetition.
Think in Collections
Whenever you have many similar values and need to perform the same operation on each value, a loop should immediately come to mind.
The for Loop
Python's for loop is used to iterate over an
iterable such as a list, string, tuple, set, dictionary,
or range.
Basic Syntax
for item in collection:
# code to execute
For example:
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit)
apple banana mango
During each iteration, the variable fruit
receives the next item from the list.
How It Works
- Python gets the first item.
- It stores that item in
fruit. - The indented code runs.
- Python gets the next item.
- The process continues until the collection ends.
Looping Through Lists
Lists are one of the most common data structures used with
for loops.
students = ["Ali", "Sara", "Ahmed", "Fatima"]
for student in students:
print(student)
Ali Sara Ahmed Fatima
Processing List Values
prices = [100, 250, 500, 750]
for price in prices:
print(price * 1.10)
Here every price is increased by 10%.
A loop is especially useful when the same calculation or operation must be performed on every item.
Looping Through Strings
A string is an iterable sequence of characters. Therefore,
you can use a for loop to process every character.
word = "Python"
for character in word:
print(character)
P y t h o n
Counting Characters
message = "hello"
count = 0
for character in message:
count += 1
print(count)
5
Looping Through Tuples
Tuples can also be processed using a for loop.
coordinates = (10, 20, 30)
for value in coordinates:
print(value)
10 20 30
The loop works because tuples are iterable.
Looping Through Sets
Sets can also be iterated using a for loop.
colors = {"red", "green", "blue"}
for color in colors:
print(color)
Sets are unordered collections. Therefore, you should not rely on a particular iteration order.
Looping Through Dictionaries
Dictionaries require special attention because they contain keys and values.
Looping Through Keys
student = {
"name": "Ali",
"age": 21,
"grade": "A"
}
for key in student:
print(key)
name age grade
Looping Through Values
for value in student.values():
print(value)
Ali 21 A
Looping Through Keys and Values
for key, value in student.items():
print(key, ":", value)
name : Ali age : 21 grade : A
Use .keys() for keys,
.values() for values, and
.items() when you need both.
The range() Function
The range() function is commonly used with
for loops when you need a sequence of numbers.
Basic range()
for number in range(5):
print(number)
0 1 2 3 4
Important Rule
range(5) starts at 0 and stops before 5.
Therefore, the values are 0 through 4.
Starting From Another Number
for number in range(1, 6):
print(number)
1 2 3 4 5
Start, Stop & Step in range()
The complete form of range() is:
range(start, stop, step)
Using a Step
for number in range(2, 11, 2):
print(number)
2 4 6 8 10
Counting Backwards
for number in range(5, 0, -1):
print(number)
5 4 3 2 1
The stop value is excluded. This is one of the most common sources of off-by-one mistakes.
Looping with Indexes
Sometimes you need both the position of an item and the item itself.
A simple approach is to use range() with
len().
fruits = ["apple", "banana", "mango"]
for index in range(len(fruits)):
print(index, fruits[index])
0 apple 1 banana 2 mango
Using enumerate()
Python provides a cleaner and more readable approach with
enumerate().
fruits = ["apple", "banana", "mango"]
for index, fruit in enumerate(fruits):
print(index, fruit)
0 apple 1 banana 2 mango
Good Practice
When you need both an item's index and its value,
enumerate() is usually clearer than
manually working with range(len(...)).
Using for with if
Loops become much more powerful when combined with conditions.
For example, we can print only even numbers.
for number in range(1, 11):
if number % 2 == 0:
print(number)
2 4 6 8 10
Filtering Data
marks = [45, 78, 91, 32, 66]
for mark in marks:
if mark >= 50:
print(mark)
78 91 66
for with else
Python allows an else block to be attached
directly to a for loop.
The else block runs when the loop finishes
normally without encountering a break.
for number in range(3):
print(number)
else:
print("Loop completed.")
0 1 2 Loop completed.
How break Changes It
for number in range(5):
if number == 3:
break
print(number)
else:
print("Loop completed.")
0 1 2
Because break stopped the loop, the
else block did not execute.
When Is for...else Useful?
It is particularly useful when searching for something and you want to perform an action only when the search completes without finding it.
Nested for Loops
A loop inside another loop is called a nested loop.
for row in range(3):
for column in range(3):
print(row, column)
0 0 0 1 0 2 1 0 1 1 1 2 2 0 2 1 2 2
For every iteration of the outer loop, the inner loop runs completely.
Multiplication Table
for number in range(1, 4):
for multiplier in range(1, 6):
print(number * multiplier, end=" ")
print()
1 2 3 4 5 2 4 6 8 10 3 6 9 12 15
Nested loops can become expensive when processing very large datasets. Always consider whether a simpler approach is possible.
Practical Real-World Examples
Example 1 — Calculate Total Sales
sales = [1200, 2500, 1800, 3200]
total = 0
for sale in sales:
total += sale
print("Total sales:", total)
Total sales: 8700
Example 2 — Calculate an Average
marks = [75, 82, 68, 91, 88]
total = 0
for mark in marks:
total += mark
average = total / len(marks)
print("Average:", average)
Average: 80.8
Example 3 — Search for a Product
products = ["Laptop", "Mouse", "Keyboard", "Monitor"]
search = "Mouse"
for product in products:
if product == search:
print("Product found!")
Product found!
Example 4 — Generate a Report
employees = {
"Ali": 75000,
"Sara": 82000,
"Ahmed": 68000
}
for name, salary in employees.items():
print(f"{name}: Rs. {salary:,}")
Ali: Rs. 75,000 Sara: Rs. 82,000 Ahmed: Rs. 68,000
Common Mistakes
1. Forgetting the Colon
for number in range(5)
print(number)
The loop statement must end with :.
2. Incorrect Indentation
for number in range(5):
print(number)
The loop body must be indented.
3. Forgetting That range() Excludes Stop
for number in range(1, 5):
print(number)
This prints 1 through 4, not 5.
4. Modifying a Collection While Iterating
Removing or changing items in a collection while iterating over that same collection can produce unexpected results. When filtering data, consider building a new collection instead.
5. Using the Wrong Variable
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit)
Choose meaningful loop variable names whenever possible.
fruit communicates more clearly than a
generic name such as x.
Practice Exercises
Exercise 1 — Print Numbers
Write a for loop that prints numbers from
1 to 10.
Exercise 2 — Even Numbers
Print all even numbers between 1 and 20.
Exercise 3 — List Processing
Create a list of five fruits and print every fruit
using a for loop.
Exercise 4 — Calculate Total
Given a list of numbers, calculate the total using a loop.
Exercise 5 — Find Positive Numbers
Given a list containing positive and negative numbers, print only the positive numbers.
Exercise 6 — Multiplication Table
Ask the user for a number and generate its multiplication table from 1 to 10.
Exercise 7 — Character Counter
Ask the user for a word and count how many characters it contains using a loop.
Exercise 8 — Student Marks
Given a list of marks, count how many students scored 50 or above.
Mini Challenge — Student Marks Analyzer
Build a small program that analyzes a list of student marks.
Your program should:
- Store several student marks in a list.
- Print every mark.
- Calculate the total.
- Calculate the average.
- Count the number of passing students.
- Count the number of failing students.
- Display the highest mark.
marks = [78, 45, 91, 63, 38, 84, 55]
total = 0
passed = 0
failed = 0
for mark in marks:
print("Mark:", mark)
total += mark
if mark >= 50:
passed += 1
else:
failed += 1
average = total / len(marks)
print("Total:", total)
print("Average:", average)
print("Passed:", passed)
print("Failed:", failed)
Your Task
Extend this program so that it also identifies the highest and lowest marks and displays the result using a clean report format.
Do not simply copy a solution. Try to design the algorithm yourself using loops, conditions and variables.
Quick Knowledge Check
1. What is the main purpose of a loop?
2. What does range(5) produce?
3. Which keyword starts a for loop?
4. What does range(2, 11, 2) generate?
5. Which method returns dictionary key-value pairs?
6. What does enumerate() provide?
7. When does a for...else block execute its else part?
8. What is a nested loop?
Lesson Summary
The for loop is one of Python's most important
tools for processing repeated data.
- Loops repeat a block of code.
forloops iterate through iterable objects.- Lists, tuples, strings and sets can be iterated directly.
- Dictionaries can be processed using keys, values or items.
range()generates sequences of numbers.- The stop value of
range()is excluded. enumerate()provides indexes and values together.- Loops can be combined with
ifstatements. for...elsecan detect normal loop completion.- Nested loops place one loop inside another.
You can now use Python loops to process collections, perform calculations, search data and automate repetitive tasks.
Ready for the Next Lesson?
Mark this lesson complete after finishing the exercises and challenge.