EZ

Eduzan

Learning Hub

Eduzan
Eduzan / Python

Loops in Python – For, While and Nested Loops

Computer Science / Python tutorial chapter - Published 2025-12-17 - Python

In Python, loops are essential structures used to execute a block of code repeatedly. There are two main types of loops: the for loop and the while loop. Both loops serve similar functions but differ in their syntax and how they check conditions. This article explains how these loops work with examples.

While Loop in Python

while loop is used to repeatedly execute a block of code as long as a specified condition remains true. When the condition becomes false, the loop stops, and execution moves to the next line after the loop.

Syntax:

while condition:
statement(s)

Example:

counter = 0
while counter < 3:
    counter += 1
    print("Hello World")

Output:

Hello World
Hello World
Hello World

Using the else Clause with a While Loop: You can attach an else statement to a while loop. This block will execute after the loop completes, unless the loop is exited prematurely with a break or an exception is raised.

Example:

counter = 0
while counter < 3:
    counter += 1
    print("Hello World")
else:
    print("Loop has finished")

Output:

Hello World
Hello World
Hello World
Loop has finished

Infinite While Loop: An infinite loop occurs when the condition always evaluates to true, resulting in continuous execution. Here’s an example:

counter = 0
while counter == 0:
    print("This will run forever!")

Output:

Amount: $150.75

For Loop in Python

The for loop in Python is used to iterate over a sequence such as a list, tuple, or string. It is ideal for traversing through elements in these data structures.

Syntax:

for element in sequence:
statement(s)

Example:

n = 5
for i in range(n):
    print(i)

Output:

0
1
2
3
4

Iterating Over Different Data Structures: The for loop can also be used to iterate over various data structures, like lists, tuples, and strings.

# List iteration
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Tuple iteration
colors = ("red", "green", "blue")
for color in colors:
    print(color)

# String iteration
word = "Python"
for letter in word:
    print(letter)

# Dictionary iteration
student_ages = {'Alice': 23, 'Bob': 25, 'Charlie': 22}
for name, age in student_ages.items():
    print(f"{name}: {age}")

Output:

apple
banana
cherry

red
green
blue

P
y
t
h
o
n

Alice: 23
Bob: 25
Charlie: 22

Using the Index in a For Loop: You can also iterate over the index of a sequence using range(len(sequence)). This allows access to each element’s index in the loop.

fruits = ["apple", "banana", "cherry"]
for index in range(len(fruits)):
    print(f"Index {index}: {fruits[index]}")

Output:

Index 0: apple
Index 1: banana
Index 2: cherry

Using the else Clause with a For Loop: As with the while loop, the else block in a for loop executes when the loop completes normally (i.e., without interruption by break).

Example:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
else:
    print("All fruits have been printed.")

Output:

apple
banana
cherry
All fruits have been printed.

Nested Loops in Python

In Python, you can place one loop inside another, which is referred to as a nested loop. A for loop can be nested inside another for loop, and similarly, a while loop can be nested inside another while loop.

Nested For Loop Syntax:

for outer_var in sequence:
for inner_var in sequence:
    statement(s)

Nested While Loop Syntax:

while condition:
while condition:
    statement(s)
statement(s)

Example of a nested for loop creating a pattern:

for i in range(1, 5):
for j in range(i):
    print(i, end=' ')
print()

Output:

1
2 2
3 3 3
4 4 4 4
End of lesson.