Loops in Python: For, While, and Nested Loops
Loops are an essential programming concept that allow you to execute a block of code repeatedly. In Python, loops are used to automate repetitive tasks, iterate over data structures, and control the flow of a program efficiently. In this post, we’ll explore the three main types of loops in Python: the for
loop, the while
loop, and nested loops.
1. For Loop
The for
loop is the most commonly used loop in Python. It is used to iterate over a sequence, such as a list, tuple, string, or range. The general syntax of a for
loop is:
for item in iterable:
# code block to be executed
Example 1: Iterating Over a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
In this example, the loop iterates over each item in the fruits
list and prints it.
Example 2: Using range()
Python’s range()
function is often used with a for
loop when you want to repeat an action a specific number of times. It generates a sequence of numbers.
for i in range(5):
print(i)
Output:
0
1
2
3
4
The range(5)
generates numbers from 0 to 4, and the loop prints each number.
Example 3: Iterating Over a String
for char in "hello":
print(char)
Output:
h
e
l
l
o
Here, we’re using the for
loop to iterate over each character in the string "hello"
.
2. While Loop
A while
loop repeatedly executes a block of code as long as the specified condition is True
. It is useful when you do not know beforehand how many times the loop needs to run.
Syntax:
while condition:
# code block to be executed
Example 1: Basic While Loop
count = 0
while count < 5:
print(count)
count += 1
Output:
0
1
2
3
4
In this example, the loop continues until the condition count < 5
is no longer true. Each time the loop runs, count
is incremented by 1.
Example 2: Infinite Loop
A while
loop can create an infinite loop if the condition never becomes False
. Be careful with this type of loop, as it can crash your program if not handled properly.
while True:
print("This loop will run forever!")
break # Use break to exit the loop
Example 3: Using else
with While Loop
The else
clause in a while
loop executes when the condition becomes False
, just like it works in a for
loop.
count = 0
while count < 3:
print(count)
count += 1
else:
print("Loop finished!")
Output:
0
1
2
Loop finished!
3. Nested Loops
A nested loop is a loop inside another loop. You can have both for
loops and while
loops nested inside each other. Nested loops are useful when you need to iterate over multi-dimensional data structures, such as lists of lists.
Example 1: Nested For Loop
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
Output:
i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1
In this example, the outer loop runs 3 times, and for each iteration of the outer loop, the inner loop runs 2 times. Thus, the inner loop’s code block is executed 6 times in total.
Example 2: Nested While Loop
i = 0
while i < 2:
j = 0
while j < 3:
print(f"i={i}, j={j}")
j += 1
i += 1
Output:
i=0, j=0
i=0, j=1
i=0, j=2
i=1, j=0
i=1, j=1
i=1, j=2
This example demonstrates a nested while
loop. The outer loop runs twice, and for each iteration, the inner loop runs three times.
Example 3: Using Nested Loops with Lists of Lists
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for element in row:
print(element, end=" ")
print() # Print a new line after each row
Output:
1 2 3
4 5 6
7 8 9
Here, we have a list of lists (a 2D matrix), and we use nested loops to iterate over each element and print them row by row.
Conclusion
Loops are a powerful feature in Python that allow you to automate repetitive tasks, iterate through collections, and implement complex algorithms.
- For loops are ideal for iterating over a known range or sequence.
- While loops are useful when you need to loop until a condition changes.
- Nested loops are helpful when working with multi-dimensional data structures.
Understanding how and when to use these loops will significantly improve your coding skills and efficiency. Whether you’re working with data processing, automating tasks, or solving algorithmic problems, loops are a fundamental concept to master.