Table of Contents
TogglePython loops allow us to execute a statement or a block of statements multiple times. Loops are essential for automating repetitive tasks, iterating over data structures, and handling complex logic efficiently.
Python provides two main types of loops, along with the ability to nest them for more complex scenarios:
The while loop repeats a block of code as long as a specified condition is True. It is useful when the number of iterations is not known in advance.
# Example of a While Loop
count = 0
while count < 5:
print("Count is:", count)
count += 1
Output:
Count is: 0 Count is: 1 Count is: 2 Count is: 3 Count is: 4
In this example, the loop continues to execute as long as count is less than 5. The count variable is incremented by 1 in each iteration.
The for loop is used to iterate over a sequence (such as a list, tuple, dictionary, string, or range). It is ideal when the number of iterations is known or when iterating over elements of a collection.
# Example of a For Loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("I love", fruit)
Output:
I love apple I love banana I love cherry
In this example, the for loop iterates over each item in the fruits list and prints a statement for each fruit.
A nested loop is a loop inside another loop. This is useful for working with multi-dimensional data structures or performing repetitive tasks within repetitive tasks.
# Example of Nested Loops
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
Here, the outer loop runs 3 times, and for each iteration of the outer loop, the inner loop runs 2 times.
Python provides control statements to modify the flow of loops. These include:
The break statement is used to exit the loop immediately when a certain condition is met. It is often used to stop the loop prematurely.
# Example of Break Statement
for num in range(10):
if num == 5:
break
print("Number:", num)
Output:
Number: 0 Number: 1 Number: 2 Number: 3 Number: 4
In this example, the loop stops executing when num equals 5.
The continue statement skips the remaining code inside the loop for the current iteration and moves to the next iteration.
# Example of Continue Statement
for num in range(5):
if num == 2:
continue
print("Number:", num)
Output:
Number: 0 Number: 1 Number: 3 Number: 4
Here, the loop skips printing when num equals 2.
The pass statement is a placeholder that does nothing. It is used when a statement is syntactically required but no action is needed.
# Example of Pass Statement
for num in range(3):
if num == 1:
pass # Do nothing
print("Number:", num)
Output:
Number: 0 Number: 1 Number: 2
In this example, the pass statement is used as a placeholder when num equals 1.
