Loops
Loops are control flow statements that allow you to repeatedly execute a block of code. Python offers two primary loop types: for and while.
For Loop
A for loop iterates over a sequence (like a list, tuple, string, or range) and executes a block of code for each item in the sequence.
Python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Iterating over a range:
Python
for i in range(5):
print(i)
While Loop
A while loop executes a block of code as long as a specified condition is true.
Python
count = 0
while count < 5:
print(count)
count += 1
Loop Control Statements
- break: Terminates the loop entirely.
- continue: Skips the current iteration and moves to the next.
- else: Optional clause executed when the loop completes normally (without break).
Python
for num in range(10):
if num == 5:
break
print(num)
for num in range(10):
if num % 2 == 0:
continue
print(num)
Nested Loops
You can have loops within loops:
Python
for i in range(3):
for j in range(2):
print(i, j)
Important Considerations
- Indentation is crucial for defining the loop body.
- Be careful with infinite loops (while loops without a clear exit condition).
- Use break and continue judiciously to control loop flow.
By understanding these loop constructs, you can effectively automate repetitive tasks and process data efficiently in your Python programs.