Python Loops
Loops in Python allow us to execute a block of code multiple times, making our programs more efficient and reducing redundancy.
For Loop
The for
loop is used to iterate over a sequence such as a list, tuple, or string.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Using Range in For Loop
for i in range(5):
print("Iteration:", i)
While Loop
The while
loop executes as long as a condition remains true.
x = 0
while x < 5:
print("Value of x:", x)
x += 1
Break Statement
The break
statement exits a loop prematurely when a condition is met.
for num in range(10):
if num == 5:
break
print(num)
Continue Statement
The continue
statement skips the current iteration and moves to the next.
for num in range(10):
if num % 2 == 0:
continue
print(num)
Nested Loops
Loops can be nested inside other loops to iterate over multiple sequences.
for i in range(3):
for j in range(3):
print(f"i={i}, j={j}")
Looping with Else
The else
block in loops executes when the loop completes without a break
statement.
for num in range(3):
print(num)
else:
print("Loop completed successfully")
Conclusion
Loops are fundamental to Python programming, allowing repetitive tasks to be handled efficiently.