One of the most powerful features in any programming language is the ability to repeat tasks efficiently. In Python, loops help you automate repetitive actions, making your code cleaner and faster.
In this post, we’ll explore the two main types of loops in Python: for and while, along with examples, use cases, and best practices.
Imagine printing numbers from 1 to 100 manually. That’s 100 lines of code! With loops, you can do it in just a few lines.
Loops are used for:
Iterating over data structures (lists, dictionaries, etc.)
Repeating tasks until a condition is met
Automating repetitive logic
The for loop is used to iterate over a sequence (like a list, tuple, string, or range).
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
apple
banana
cherry
for i in range(5):
print(i)
0
1
2
3
4
The while loop runs as long as a condition is true.
count = 5
while count > 0:
print(count)
count -= 1
5
4
3
2
1
Python gives you tools to control loop behavior:
break: Exit the loop early
continue: Skip the current iteration
pass: Do nothing (placeholder)
for i in range(10):
if i == 5:
break
print(i)
0
1
2
3
4
Avoid infinite loops unless necessary.
Use for loops when iterating over known sequences.
Use while loops when the end condition isn’t known in advance.
Keep loop bodies clean and readable.
Loops are essential for writing efficient Python code. Whether you're processing data, building algorithms, or automating tasks, mastering loops will take your coding skills to the next level.
Next up in the series: Data Structures in Python