What are Loops in Python?
Loops are used in Python to execute a block of code multiple times. Python provides two primary loop types:
- for loop – Iterates over a sequence (e.g., list, tuple, dictionary, string).
- while loop – Runs as long as a specified condition is true.
For Loop
The for loop is used when you want to iterate over a sequence.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
While Loop
The while loop is used when you want to repeat a block of code as long as a condition is true.
x = 0
while x < 5:
print(x)
x += 1
Loop Control Statements
Python provides loop control statements to manage the flow of loops:
break– Exits the loop completely.continue– Skips the rest of the loop iteration and moves to the next one.pass– Placeholder for empty loops.
Break Statement Example
for num in range(10):
if num == 5:
break
print(num)
Continue Statement Example
for num in range(5):
if num == 2:
continue
print(num)
Nested Loops
A loop inside another loop is called a nested loop.
for i in range(3):
for j in range(2):
print(f"i: {i}, j: {j}")
Else in Loops
Python allows an else block in loops, which executes when the loop finishes normally (i.e., without encountering a break).
for num in range(3):
print(num)
else:
print("Loop completed")