Introduction
Loops are fundamental in any programming language, and Python is no exception. They allow us to execute a block of code repeatedly, which is particularly useful for tasks involving iteration, automation, or repetitive calculations.
In this blog, weโll explore the types of loops in Python, including:
for loops
while loops
nested loops
loop control statements (break, continue, and pass)
Each section comes with clean code examples and inline comments to illustrate their usage and expected output.
๐ง What Are Loops in Python?
A loop in Python is used to run a block of code multiple times. The primary two types are:
for loops โ used for iterating over a sequence (like a list, tuple, dictionary, string, or range).
while loops โ run as long as a condition is True.
๐ 1. for Loop in Python
The for loop iterates over a sequence (like a list or a string) and executes the block of code for each item.
Example 1: Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Output:
# apple
# banana
# cherry
Example 2: Using range() with for loop
for i in range(5):
print(i)
# Output:
# 0
# 1
# 2
# 3
# 4
๐ 2. while Loop in Python
A while loop repeats a block of code as long as a condition is True.
Example: Counting from 1 to 5
i = 1
while i <= 5:
print(i)
i += 1
# Output:
# 1
# 2
# 3
# 4
# 5
๐ 3. Nested Loops
A nested loop is a loop inside another loop. The inner loop completes all its iterations for every single iteration of the outer loop.
Example: Multiplication table using nested loops
for i in range(1, 4):
for j in range(1, 4):
print(i * j, end=" ")
print()
# Output:
# 1 2 3
# 2 4 6
# 3 6 9
๐งช 4. Loop Control Statements
Python provides several control statements to change the flow of loops:
4.1 break Statement
Stops the loop prematurely when a condition is met.
for i in range(10):
if i == 5:
break
print(i)
# Output:
# 0
# 1
# 2
# 3
# 4
4.2 continue Statement
Skips the current iteration and moves to the next one.
for i in range(5):
if i == 2:
continue
print(i)
# Output:
# 0
# 1
# 3
# 4
4.3 pass Statement
A placeholder that does nothing โ used when a statement is syntactically required but you donโt want to execute any code.
for i in range(3):
pass # Placeholder for future code
print("Loop executed with pass")
# Output:
# Loop executed with pass
๐ Conclusion
Loops are a crucial part of any Python programmerโs toolkit. Whether you're reading files, processing lists, or building algorithms, understanding how and when to use different types of loops โ and controlling them with break, continue, and pass โ is essential.
Keep practicing with your own examples and try using loops in small projects like:
Number guessing games
Basic calculators
Pattern generators (stars, pyramids)