Loops in Python
Loops allow executing a block of code repeatedly as long as a condition is met. They are fundamental for automating repetitive tasks and traversing data structures like lists, dictionaries, or text strings.
Python has two main types of loops:
for Loopβ
It is used to iterate over elements of a sequence (like a list, a string, or a range of numbers).
Syntax:β
for variable in iterable:
# Code block
Example:β
fruits = ["apple", "pear", "grape"]
for fruit in fruits:
print(fruit)
> Result:
apple
pear
grape
You can also use for with the range() function to repeat a block a certain number of times:
for i in range(5):
print(i)
> Result:
0
1
2
3
4
while Loopβ
Repeats the code block while a condition is true.
Syntax:β
while condition:
# Code block
Example:β
counter = 1
while counter <= 3:
print(counter)
counter += 1
> Result:
1
2
3
Useful keywordsβ
| Keyword | Description |
|---|---|
break | Exits the loop immediately. |
continue | Skips the current iteration and moves to the next one. |
else | Executes if the loop finishes without having used break. |
Example with break:β
for number in range(10):
if number == 5:
break
print(number)
> Result:
0
1
2
3
4
Example with continue:β
for number in range(5):
if number == 2:
continue
print(number)
> Result:
0
1
3
4
Example with else in loops:β
for i in range(3):
print(i)
else:
print("The loop finished correctly")
> Result:
0
1
2
The loop finished correctly
Differences between for and whileβ
| Feature | for | while |
|---|---|---|
| Ideal for... | Iterating over sequences | Executing while a condition is met |
| Iteration control | Based on the iterable | Based on logical condition |
| Infinite loop risk | Low | High if the condition is not changed |
Best practicesβ
- Use
forwhen you know how many times you need to iterate or have an iterable structure. - Use
whilewhen you do not know for sure how many iterations will be made. - Always make sure loops have a clear exit condition.
- Avoid nesting multiple loops if you can simplify the logic.
- Use meaningful variable names inside loops.
Loops are fundamental tools for automating tasks, traversing data structures, and controlling the flow of execution in your Python programs. Mastering their use will help you write more efficient, clean, and powerful code.