Python for Loop VS while Loop
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 a fundamental concept in programming, allowing you to repeat blocks of code. In Python, both
for
and
while
loops serve this purpose.
However, the key question is: When should you use each type?
Both types of loops are crucial tools in Python programming. Understanding when to use each will help you write more efficient, readable, and maintainable code.
Let's compare for loops and while loops with examples to better understand their use cases.
Let's compare how the
for
loop and the
while
loop can be used to accomplish the same task: calculating the sum of numbers from
1
to
5.
Using a For Loop
total = 0
for i in range(1, 6):
total += i
print(total) # Output: 15
Using a While Loop
i = 1
total = 0
while i <= 5:
total += i
i += 1
print(total) # Output: 15
Both loops achieve the same result.
However, the
for
loop is cleaner and more concise when the number of iterations is known ahead of time. The
while
loop, on the other hand, requires manual initialization and updating of the loop variable (i
).
If you know in advance how many times a task needs to be repeated, a
for
loop is generally the better choice for simplicity and readability.
In some cases, you don't know in advance how many iterations are needed. For instance, consider the task of finding the smallest number that, when added incrementally, reaches a given sum.
Using a While Loop
target_sum = 15
i = 1
total = 0
while total != target_sum:
total += i
i += 1
print(i - 1) # Output: 5
Can this be done with a for loop?
Technically, yes—but not efficiently. A
for
loop requires a predefined range. To handle this task, you'd need to set up an arbitrarily large range and then add a
break
condition.
target_sum = 15
total = 0
for i in range(1000000): # Large range to be sure we reach the target sum
total += i
if total == target_sum:
print(i) # Output: 5
break
While this works, it's not ideal. The
while
loop is more intuitive and efficient in this case, as it doesn't require guessing the range or dealing with unnecessary iterations.
for
loops when the number of iterations is fixed or known in advance.while
loops when the number of iterations is uncertain, but you know the stopping condition.