What is a Loop in Python
In Python, a loop (or iteration) is a programming construct that allows a block of code to be executed repeatedly. Loops are fundamental for automating repetitive tasks, processing lists of data, or continuing an operation until a specific condition is met.
The for loop in Python is the most versatile and pythonic. It is often used with the range() function or to iterate over sequences like lists, tuples, and strings.
For Loop
The for loop in Python is used to iterate over a sequence (such as a list, tuple, dictionary, set, or string) or other iterable objects. The loop iterates over the elements of the sequence, allowing you to execute a block of code for each item.
# For loop with range
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# Iteration over a list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(f"I like {fruit}
tl")While Loop
The while loop executes a block of code as long as a condition remains true. It is useful when the exact number of iterations is not known.
count = 0
while count 5:
print(count)
count += 1 # increment, otherwise infinite loop!Break and Continue
The break and continue statements control the flow of loops. break immediately stops the loop, while continue skips the rest of the loop body and moves to the next iteration.
# Example with break
for i in range(10):
if i == 5:
break # exits when i reaches 5
print(i) # 0-4
# Example with continue
for i in range(5):
if i == 2:
continue # skips i=2
print(i) # 0, 1, 3, 4Nested Loops
Loops can be nested to handle two-dimensional structures like matrices or grids.
# 3x3 matrix
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for element in row:
print(element, end=' ')
print()Loops over Dictionaries
Python allows iterating over dictionaries, generating keys, values, or key-value pairs.
points = {"player1": 150, "player2": 200, "player3": 175}
for player, score in points.items():
print(f"{player}: {score} points")Nested Loop Pattern
A common pattern in programming is the "nested loop" or nested loop, which is often used for:
Infinite Loop and Safety
It is crucial to avoid infinite loops. Always ensure that termination conditions are met:
# ❌ Error: infinite loop
x = 0
while True:
print(x)
# missing x += 1
# ✅ Correct
x = 0
while x 100:
print(x)
x += 10