The while Loop in Python

In this post I explain the Python while loop, including break, continue, else, and nested loops.
TopicsPython

The while Loop in Python

The while loop is one of the core programming constructs. It lets a program repeat a block of code.

What the while Loop Does

A while loop keeps running as long as its condition stays true, that is, as long as it evaluates toTrue.

Consider this example: find the first power of two that is greater than 1000.

n = 1
i = 0
target = 1000
while n < target:
    n *= 2
    i += 1

n  # 1024
i  # 10
2 ** i  # 1024

After the keyword while comes the loop condition. The loop runs while n < target.

The colon marks the end of the condition and the start of the block. The operator *= is shorthand for n = n * 2, and += is shorthand for i = i + 1.

The variable i stores the number of iterations needed until the condition became false. We found the first power of two greater than 1000, which is 1024, or the tenth power of two.

The break Keyword

break is used to stop the loop early.

Now let us find the first odd power of two that is greater than 1000:

n = 1
i = 0
target = 1000
while True:
    if n > target and i % 2 == 1:
        break
    n *= 2
    i += 1

n  # 2048
i  # 11
2 ** i  # 2048

This example uses an infinite loop with while True. It always starts as true. The loop stops only when break runs. Here that happens when n > target and i is odd.

The continue Keyword

continue is used to skip the current iteration and move straight to the next one.

Let us calculate the sum of all even numbers below 15:

n = 1
sum = 0
while n < 15:
    if n % 2 != 0:
        n += 1
        continue
    sum += n
    n += 1

sum  # 56
# 2 + 4 + 6 + 8 + 10 + 12 + 14 = 56

The else Keyword

You can place an else block after a while loop. It runs when the loop finishes because the condition became false. If the loop stops with break, the else block is skipped.

i = 1
while i > 0:
    i -= 1
else:
    result = "else ran"

result  # 'else ran'
i  # 0

Here result exists because the loop ended normally when i became 0.

while True:
    break
else:
    no_result = "else did not run"

# NameError: name 'no_result' is not defined

In this case the else block did not run because the loop was interrupted by break.

Nested Loops

Like other code blocks, a while loop can be placed inside another while loop.