When writing Python programs, we often need to execute the same operation repeatedly.
It could be processing records, checking values in a list, reading a file line by line, processing API responses, or performing repetitive data-processing tasks.
Writing the same code again and again is not practical.
This is where loops and flow control become important.
Python provides simple ways to repeat operations, make decisions, skip specific iterations, stop execution when required, and control the normal flow of a program.
In this post, we'll understand the important concepts behind Python loops and flow control with practical examples.
*What Is a Loop in Python?
*
A loop allows us to execute a block of code repeatedly.
For example, if we want to print numbers from 1 to 5, we could write:
print(1)
print(2)
print(3)
print(4)
print(5)
But using a loop makes the code much simpler:
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
The main advantage of loops is that they reduce repetitive code.
Loops are commonly used for:
- Processing lists
- Processing strings
- Reading files
- Processing database records
- Handling API responses
- Data transformation
- Automation
- Data analysis
- ETL and data-processing tasks
The Two Main Types of Loops in Python
Python mainly provides two types of loops:
- "for" loop
- "while" loop
They both repeat code, but they are generally used in different situations.
for Loop
A "for" loop is commonly used to iterate through an iterable.
For example:
fruits = ["Apple", "Banana", "Mango"]
for fruit in fruits:
print(fruit)
Output:
Apple
Banana
Mango
The loop takes one item at a time from the collection.
A "for" loop can be used with lists, strings, tuples, ranges, and many other iterable objects.
For example:
name = "Python"
for character in name:
print(character)
Output:
P
y
t
h
o
n
while Loop
A "while" loop continues executing as long as its condition is true.
count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
The important part here is:
count += 1
The value changes during each iteration.
Eventually, "count <= 5" becomes false and the loop stops.
A "while" loop is useful when the number of iterations depends on a condition that can change during execution.
for vs while
A simple way to think about them is:
for loop
Use it when you are iterating through a sequence or iterable.
for item in items:
print(item)
while loop
Use it when a condition controls whether the loop should continue.
while condition:
# code
The choice should depend on the problem rather than simply on whether the number of iterations is known.
What Is an Iterable?
An iterable is an object whose values can be accessed one at a time.
Common examples include:
list
tuple
string
set
dictionary
range
For example:
numbers = [10, 20, 30]
for number in numbers:
print(number)
The "for" loop gets each value from the iterable.
Understanding iterables is important because Python's "for" loop is built around iteration.
Using range()
The "range()" function is commonly used with "for" loops.
There are three common forms:
range(stop)
range(start, stop)
range(start, stop, step)
For example:
for i in range(5):
print(i)
Output:
0
1
2
3
4
Notice that "5" is not included.
We can specify a starting value:
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
We can also specify a step:
for i in range(0, 11, 2):
print(i)
Output:
0
2
4
6
8
10
The "step" controls how much the value changes during each iteration.
Loop Control Variables
A loop control variable can be used to control how long a loop continues.
For example:
count = 1
while count <= 5:
print(count)
count += 1
Here, "count" starts at "1" and increases after every iteration.
When it reaches "6", the condition becomes false.
This is especially important when working with "while" loops.
Infinite Loops
An infinite loop is a loop that never reaches a condition that stops it.
For example:
while True:
print("Running...")
Because the condition is always "True", the loop continues indefinitely.
An infinite loop can also happen accidentally:
count = 1
while count <= 5:
print(count)
The problem is that "count" never changes.
A corrected version is:
count = 1
while count <= 5:
print(count)
count += 1
Whenever you write a "while" loop, ask:
What will eventually make this condition false?
break, continue and pass
Python provides three important statements for controlling loop execution:
break
continue
pass
They have completely different purposes.
break
"break" stops the entire loop.
for i in range(1, 6):
if i == 3:
break
print(i)
Output:
1
2
When "i" becomes "3", the loop terminates.
This is useful when the required result has already been found and there is no reason to continue.
continue
"continue" skips the current iteration.
for i in range(1, 6):
if i == 3:
continue
print(i)
Output:
1
2
4
5
The loop continues after skipping "3".
pass
"pass" does nothing.
for i in range(5):
if i == 2:
pass
print(i)
Output:
0
1
2
3
4
So the easiest way to remember them is:
break β stop the loop
continue β skip the current iteration
pass β do nothing
Nested Loops
A loop inside another loop is called a nested loop.
For example:
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
The inner loop executes completely for each iteration of the outer loop.
Nested loops are useful for:
- Tables
- Grids
- Matrices
- Multi-dimensional data
- Combinations
However, they can become expensive when working with large datasets, so unnecessary nested loops should be avoided.
enumerate()
Sometimes we need both the position and the value while iterating.
Python provides "enumerate()" for this purpose.
fruits = ["Apple", "Banana", "Mango"]
for index, fruit in enumerate(fruits):
print(index, fruit)
Output:
0 Apple
1 Banana
2 Mango
This is cleaner than maintaining a separate counter.
Loop else
Python has an interesting feature that allows an "else" block to be used with loops.
The loop "else" executes when the loop finishes normally without "break".
For example:
for i in range(5):
print(i)
else:
print("Loop completed")
The "else" block executes because the loop finishes normally.
But if "break" terminates the loop:
for i in range(5):
if i == 3:
break
print(i)
else:
print("Loop completed")
The "else" block does not execute.
A useful way to remember it is:
Loop "else" runs when the loop completes without "break".
Simulating a do-while Loop
Python does not have a separate "do-while" statement.
However, similar behavior can be created using "while True" and "break".
while True:
value = input("Enter a positive number: ")
if int(value) > 0:
break
The body executes first, and the loop can then be terminated when the required condition is satisfied.
This is useful when an operation needs to execute at least once before checking whether the loop should continue.
Iterating in Reverse
The "range()" function can also be used to iterate backwards.
for number in range(10, 0, -1):
print(number)
Output:
10
9
8
7
6
5
4
3
2
1
The "-1" tells Python to decrease the value after every iteration.
Printing Every Other Number
The "step" argument of "range()" can be used to skip values.
for number in range(0, 11, 2):
print(number)
Output:
0
2
4
6
8
10
The value increases by "2" each time.
Handling Exceptions Inside a Loop
When processing many values, one invalid value should not always stop the complete operation.
Python allows us to handle exceptions inside a loop.
numbers = [10, 5, 0, 3]
for number in numbers:
try:
result = 100 / number
print(result)
except ZeroDivisionError:
print("Cannot divide by zero")
When the value is "0", the exception is handled and the loop continues.
This pattern is useful when processing:
- Data records
- Files
- API responses
- User input
- Large datasets
It makes the program more robust because one problematic record does not necessarily stop the complete process.
How to Write Better Python Loops
Once the logic is correct, we can also think about readability and performance.
Use built-in functions
For some operations, Python's built-in functions can replace manual loops.
For example:
total = sum(numbers)
Other useful functions include:
min(numbers)
max(numbers)
Avoid unnecessary calculations
If a calculation does not change during the loop, perform it outside the loop when possible.
Avoid unnecessary nested loops
Nested loops can become expensive as the amount of data increases.
Use appropriate data structures
Sets and dictionaries can be useful for efficient lookup operations.
Stop processing when the answer is known
Use "break" when there is no reason to continue.
Consider vectorized operations for data processing
When working with libraries such as Pandas and NumPy, a Python loop is not always the best solution. Vectorized operations can often be more appropriate for large datasets.
Why Loops Matter in Data Engineering and Data Analytics
Loops are basic Python concepts, but they appear in many real-world tasks.
For example, they can be used while:
- Processing records
- Validating data
- Transforming values
- Reading files
- Calling APIs
- Handling errors
- Automating repetitive operations
- Building data-processing scripts
As your Python knowledge grows, you will also learn when not to use a loop.
For example, Pandas and NumPy provide operations that can process collections of data more efficiently than manually iterating through every row in many situations.
So the goal is not simply to learn loop syntax.
The goal is to understand how and when to control program execution effectively.
Going Deeper: Python Loops and Flow Control
The examples above give you the foundation.
But if you are preparing for technical interviews or want to understand the topic more deeply, there are many details worth exploringβsuch as iterable behavior, loop termination, "range()", "enumerate()", nested loops, loop "else", "break" and "continue", do-while behavior, optimization, and exception handling.
I have put those deeper topics into a separate 25-question Python Loops and Flow Control technical Q&A resource, with detailed explanations and examples.
π "Explore the detailed Python Loops and Flow Control questions and answers" (https://www.sankalandtech.com/Tutorials/Python/interview-questions/python-control-structures-loops.html)
You can use this post to understand the concepts first, and then use the detailed Q&A resource when you want to test your understanding or go deeper into the technical side of Python loops.
Final Takeaway
Python loops are more than just a way to repeat code.
They are a fundamental part of controlling program execution.
The important concepts to remember are:
for β iterate over an iterable
while β repeat while a condition is true
range() β generate a sequence of numbers
enumerate β get index and value
break β stop the loop
continue β skip the current iteration
pass β do nothing
nested loop β loop inside another loop
loop else β execute when the loop completes normally
Start with small examples.
Run the code.
Change the conditions.
Predict the output.
Then move to real-world data-processing problems.
That is where Python loops and flow control become much more useful.
Top comments (0)