Home Course Roadmap
Lesson 25 · Control Flow Beginner

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.

40–50 minutes
Control Flow
Python Foundations
0%

What You Will Learn

  • Understand why loops are important in programming.
  • Write and understand Python for loops.
  • 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...else structure.
  • Apply loops to practical programming problems.
01

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.

Without a loop
print(1)
print(2)
print(3)
print(4)
print(5)
With a loop
for number in range(1, 6):
    print(number)
Output
1
2
3
4
5
Key Idea

Loops allow a program to perform repetitive work automatically instead of repeating code manually.

02

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.

03

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

Syntax
for item in collection:
    # code to execute

For example:

Example
fruits = ["apple", "banana", "mango"]

for fruit in fruits:
    print(fruit)
Output
apple
banana
mango

During each iteration, the variable fruit receives the next item from the list.

How It Works

  1. Python gets the first item.
  2. It stores that item in fruit.
  3. The indented code runs.
  4. Python gets the next item.
  5. The process continues until the collection ends.
04

Looping Through Lists

Lists are one of the most common data structures used with for loops.

Example
students = ["Ali", "Sara", "Ahmed", "Fatima"]

for student in students:
    print(student)
Output
Ali
Sara
Ahmed
Fatima

Processing List Values

Example
prices = [100, 250, 500, 750]

for price in prices:
    print(price * 1.10)

Here every price is increased by 10%.

Practical Thinking

A loop is especially useful when the same calculation or operation must be performed on every item.

05

Looping Through Strings

A string is an iterable sequence of characters. Therefore, you can use a for loop to process every character.

Example
word = "Python"

for character in word:
    print(character)
Output
P
y
t
h
o
n

Counting Characters

Example
message = "hello"

count = 0

for character in message:
    count += 1

print(count)
Output
5
06

Looping Through Tuples

Tuples can also be processed using a for loop.

Example
coordinates = (10, 20, 30)

for value in coordinates:
    print(value)
Output
10
20
30

The loop works because tuples are iterable.

07

Looping Through Sets

Sets can also be iterated using a for loop.

Example
colors = {"red", "green", "blue"}

for color in colors:
    print(color)
Remember

Sets are unordered collections. Therefore, you should not rely on a particular iteration order.

08

Looping Through Dictionaries

Dictionaries require special attention because they contain keys and values.

Looping Through Keys

Example
student = {
    "name": "Ali",
    "age": 21,
    "grade": "A"
}

for key in student:
    print(key)
Output
name
age
grade

Looping Through Values

Example
for value in student.values():
    print(value)
Output
Ali
21
A

Looping Through Keys and Values

Using items()
for key, value in student.items():
    print(key, ":", value)
Output
name : Ali
age : 21
grade : A
Remember

Use .keys() for keys, .values() for values, and .items() when you need both.

09

The range() Function

The range() function is commonly used with for loops when you need a sequence of numbers.

Basic range()

Example
for number in range(5):
    print(number)
Output
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

Example
for number in range(1, 6):
    print(number)
Output
1
2
3
4
5
10

Start, Stop & Step in range()

The complete form of range() is:

Syntax
range(start, stop, step)

Using a Step

Example
for number in range(2, 11, 2):
    print(number)
Output
2
4
6
8
10

Counting Backwards

Negative step
for number in range(5, 0, -1):
    print(number)
Output
5
4
3
2
1
Watch the Stop Value

The stop value is excluded. This is one of the most common sources of off-by-one mistakes.

11

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().

Using indexes
fruits = ["apple", "banana", "mango"]

for index in range(len(fruits)):
    print(index, fruits[index])
Output
0 apple
1 banana
2 mango

Using enumerate()

Python provides a cleaner and more readable approach with enumerate().

Recommended approach
fruits = ["apple", "banana", "mango"]

for index, fruit in enumerate(fruits):
    print(index, fruit)
Output
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(...)).

12

Using for with if

Loops become much more powerful when combined with conditions.

For example, we can print only even numbers.

Example
for number in range(1, 11):

    if number % 2 == 0:
        print(number)
Output
2
4
6
8
10

Filtering Data

Example
marks = [45, 78, 91, 32, 66]

for mark in marks:

    if mark >= 50:
        print(mark)
Output
78
91
66
13

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.

Example
for number in range(3):
    print(number)
else:
    print("Loop completed.")
Output
0
1
2
Loop completed.

How break Changes It

Example
for number in range(5):

    if number == 3:
        break

    print(number)

else:
    print("Loop completed.")
Output
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.

14

Nested for Loops

A loop inside another loop is called a nested loop.

Basic nested loop
for row in range(3):

    for column in range(3):
        print(row, column)
Output
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

Practical example
for number in range(1, 4):

    for multiplier in range(1, 6):

        print(number * multiplier, end=" ")

    print()
Output
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
Be Careful

Nested loops can become expensive when processing very large datasets. Always consider whether a simpler approach is possible.

15

Practical Real-World Examples

Example 1 — Calculate Total Sales

Sales calculation
sales = [1200, 2500, 1800, 3200]

total = 0

for sale in sales:
    total += sale

print("Total sales:", total)
Output
Total sales: 8700

Example 2 — Calculate an Average

Student marks
marks = [75, 82, 68, 91, 88]

total = 0

for mark in marks:
    total += mark

average = total / len(marks)

print("Average:", average)
Output
Average: 80.8

Example 3 — Search for a Product

Product search
products = ["Laptop", "Mouse", "Keyboard", "Monitor"]

search = "Mouse"

for product in products:

    if product == search:
        print("Product found!")
Output
Product found!

Example 4 — Generate a Report

Report generation
employees = {
    "Ali": 75000,
    "Sara": 82000,
    "Ahmed": 68000
}

for name, salary in employees.items():
    print(f"{name}: Rs. {salary:,}")
Output
Ali: Rs. 75,000
Sara: Rs. 82,000
Ahmed: Rs. 68,000
16

Common Mistakes

1. Forgetting the Colon

Incorrect
for number in range(5)
    print(number)

The loop statement must end with :.

2. Incorrect Indentation

Incorrect
for number in range(5):
print(number)

The loop body must be indented.

3. Forgetting That range() Excludes Stop

Example
for number in range(1, 5):
    print(number)

This prints 1 through 4, not 5.

4. Modifying a Collection While Iterating

Potential Problem

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

Example
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.

17

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.

18

Mini Challenge — Student Marks Analyzer

Build a small program that analyzes a list of student marks.

Your program should:

  1. Store several student marks in a list.
  2. Print every mark.
  3. Calculate the total.
  4. Calculate the average.
  5. Count the number of passing students.
  6. Count the number of failing students.
  7. Display the highest mark.
Starter Code
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.

Challenge Goal

Do not simply copy a solution. Try to design the algorithm yourself using loops, conditions and variables.

19

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?

20

Lesson Summary

The for loop is one of Python's most important tools for processing repeated data.

  • Loops repeat a block of code.
  • for loops 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 if statements.
  • for...else can detect normal loop completion.
  • Nested loops place one loop inside another.
You've Got the Foundation

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.