Loops in Python – For, While and Nested Loops

Loops in 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

Loop Control Statements

Loop control statements modify the flow of execution within loops. Python has three primary control statements:

1. continue: Skips the current iteration and moves to the next iteration.
2. break: Exits the loop immediately.
3. pass: Does nothing and moves to the next iteration.

1. Using continue: This code skips the iteration when encountering a specific letter:

for letter in "programming":
if letter == "r":
    continue
print(letter)

Output:

p
o
g
a
m
m
i
n
g

Output:

p

Using pass: The pass statement is used when you want an empty loop body or placeholder for future code.

for letter in "programming":
    pass
print("Loop completed.")

Output:

Loop completed.

Using breakThe break statement is used to exit a loop immediately when a specified condition is met. It terminates the loop’s execution and transfers control to the statement following the loop.

Example with break:
This code stops the loop when a specific letter is encountered.

# Example of break
for letter in "python":
    if letter == "h":
        break  # Exit the loop when the letter 'h' is encountered
    print("Current letter:", letter)

Output:

Current letter: p
Current letter: y
Current letter: t

How the for Loop Works Internally

Python’s for loop iterates over iterable objects such as lists, sets, and dictionaries. Here’s how it works:

1. Python creates an iterator object from the iterable.
2. It repeatedly fetches the next item from the iterator using the next() function until it raises a StopIteration exception.

Example of manually iterating through a list using an iterator:

fruits = ["apple", "orange", "kiwi"]
iterator = iter(fruits)
while True:
    try:
        fruit = next(iterator)
        print(fruit)
    except StopIteration:
        break

Output:

apple
orange
kiwi

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *