Comparing while
and for
Loops¶
As it turns out, anything that can be accomplished with a for
loop can also be done with a while
loop. However, for
loops require fewer lines of code than a similar while
loop, and are typically easier to read. So why would we ever use a while
loop? As it turns out, while
loops are a more flexible tool than for
loops. There are some tasks that we cannot accomplish with a for
loop, but can with a while
loop.
When we create a for loop, we tell the loop (either explicitly, or programmatically) how many times it will run. As soon as Python encounters a statement starting with for
, it will know how many times that the loop will execute (assuming that no errors are encountered). On the other hand, while
loops will continue to execute for as long as some condition is true. Python does not know how many times it will execute a while
loop that it enounters, but it will keep doing so until the condition is no longer true. For this reason, while
loops are well-suited for situations in which we do not know how many times the loop will need to execute, either because it would be difficult to calculate, or because the condition depends on some external factors (such as user input) that Python has no way of knowing in advance.
As a somewhat superficial example, let’s say that you wanted to know the smallest positive integer n
for which \(n^5 > \left(7 n + 10 \right)^4\). If we could mathematically solve the inequality, we could get the answer, but that is certainly not easy to do. We can, however, simply start n
at 1, and then use a while
loop to increment n
for as long as \(n^5 \leq \left(7 n + 10 \right)^4\)
n = 1
while n**5 <= (7*n + 10)**4:
n += 1
print(n)
2407
print(n**5)
print((7*n + 10)**4)
80794249545628807
80784351430226161