Python Looping Techniques
This article is a complementary resource to the Learn Python Basics course.
This article is a complementary resource to the Learn Python Basics course.
Loops are essential in Python for automating repetitive tasks. But the real magic happens when you use them creatively and efficiently.
This blog skips the theory and dives straight into practical tips, tricks, and real-world applications of loops.
You use for loops when the number of iterations is known in advance or when you need to iterate over a sequence such as a list, tuple, or range.
Let's look at an example.
for i in range(5):
print(i)
Here, the
for
loop iterates the range of numbers from
0
to
4
and prints each number. It's efficient when the task has a predictable iteration count.
You use
while
loops when the number of iterations isn't predetermined and depends on a condition being true. For example,
num = 1
while num <= 100:
print(num)
num *= 2
Here, the
while
loop executes as long as the condition (num <= 100
) is
true
. This makes it ideal for scenarios where the stopping point is fixed, but the number of iterations isn't fixed in advance.
Sometimes, you don't want a loop to run until its natural end. In such cases, Python provides the
break
and
continue
statements to control the flow of the loop.
These are especially useful when you need to exit early or skip certain iterations based on specific conditions.
You use
break
when you want to
stop the loop early
based on a specific condition.
This is especially helpful when searching for an item where further iterations are unnecessary once the condition is met.
Let's look at an example.
numbers = [1, 3, 5, 8, 9, 11]
for num in numbers:
if num % 2 == 0: # Check if the number is even
print(f"First even number found: {num}")
break # Exit the loop as soon as the first even number is found
Output
First even number found: 8
Here, the loop exits immediately after finding the first even number, optimizing performance by avoiding unnecessary iterations.
Use
continue
when you want to
skip the current iteration
based on a condition but keep the loop running for the remaining elements.
It is particularly useful when you want to ignore specific cases without breaking the loop entirely. For example,
numbers = [1, 2, 3, 4, 5, 6]
for num in numbers:
if num % 2 != 0: # Check if the number is odd
continue # Skip odd numbers
print(num)
Output
2 4 6
In this case, odd numbers are skipped, and the loop continues with the next iteration, printing only even numbers.
Efficient loop design can significantly improve the performance of your code. Here are three key tips to optimize loops:
1. Define Variables Outside the Loop
Calculations or variables that don't change should be defined outside the loop to reduce redundant computations.
Let's look at an example.
result = 2 ** 10 # calculated once
for i in range(5):
print(result)
Output
1024 1024 1024 1024 1024
Here, the
result
variable is calculated outside the loop, avoiding unnecessary recalculations during each iteration.
2. Avoid Recalculating Inside Loops
If you're reusing results, store them in variables instead of recalculating each time.
my_list = [1, 2, 3, 4, 5]
length = len(my_list) # Calculate length once
for i in range(length):
print(my_list[i])
Output
1 2 3 4 5
In this case,
len(my_list)
is calculated only once, saving processing time for large lists.
3. Run Loops in Descending Order if Necessary
For certain tasks like reversing sequences, looping in descending order can simplify logic and improve readability. For example,
for i in range(5, 0, -1):
print(i)
Output
5 4 3 2 1
Here, the loop iterates in reverse order, often useful for operations like countdowns or reverse processing.
Loops are incredibly versatile, and their applications go beyond basic iterations. These practical techniques demonstrate how to handle real-world challenges efficiently using loops.
Iterating Until Valid Input
Sometimes, you need to ensure the user provides valid input. A
while
loop is ideal for repeatedly asking for input until the condition is met.
Let's look at an example.
while True:
number = int(input("Enter a positive number: "))
if number > 0:
break
print(f"You entered: {number}")
Output
Enter a positive number: -5 Enter a positive number: 0 Enter a positive number: 10 You entered: 10
Here, the
while True
ensures that only valid input (a positive number) is accepted.
Looping Without a Variable
When the loop variable isn't needed, use
_
as a convention to indicate it's unused. For example,
for _ in range(5):
print("Hello, world!")
Output
Programiz Pro Programiz Pro Programiz Pro Programiz Pro Programiz Pro
In this example,
_
signifies that the loop variable isn't used in the loop body.
When loops don't behave as expected, debugging becomes crucial. By tracking progress and identifying issues, you can pinpoint errors and fix them effectively.
Here are some techniques to debug your loops.
Track Iterations
Insert print statements to monitor loop progress during debugging. For example,
for i in range(5):
print(f"Iteration: {i}")
Output
Iteration: 0 Iteration: 1 Iteration: 2 Iteration: 3 Iteration: 4
Here, the print statement helps track the loop's current iteration, making debugging easier.
Watch for Infinite Loops
Ensure your loop has an achievable exit condition to avoid infinite loops.
count = 0
while True:
print("Running...")
count += 1
if count > 10: # Exit after 10 iterations
break
Output
Running... Running... Running... Running... Running... Running...
In this example, the
count
variable is used to stop the loop after a fixed number of iterations, preventing an infinite loop.