Python offers two primary loop constructs—the for loop and the while loop—that allow developers to execute a block of code repeatedly. Understanding when and how to use each is fundamental to efficient programming.
For Loop
The for loop is used to iterate over a sequence (like a list, tuple, string, or range) or any iterable object. Its syntax is straightforward:
for item in sequence:
# code to execute
For example, to print each element of a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
This will output:
apple
banana
cherry
The range() function is commonly used with for loops to repeat an action a specific number of times:
for i in range(5):
print(i) # prints 0,1,2,3,4
While Loop
The while loop continues as long as a given condition remains True. Its basic structure:
while condition:
# code to execute
A simple countdown example:
count = 5
while count > 0:
print(count)
count -= 1
This prints:
5
4
3
2
1
Important Keywords
break: Exits the loop immediately.continue: Skips the rest of the current iteration and moves to the next one.else: Can be used with bothforandwhileloops; the else block executes when the loop finishes normally (without abreak).
Choosing Between For and While
- Use a
forloop when you know the number of iterations in advance or are iterating over a collection. - Use a
whileloop when the loop should run until a condition changes, and the number of iterations is not predetermined.
Mastering loops is essential for tasks like data processing, automation, and algorithm implementation. Practice with examples to build confidence.