The Python while-else Clause

Introduction

The Python whileelse clause is an additional, optional syntax Python’s while loop supports, similar to the else clause in the for loop. It enables you to execute a code block after the loop has finished normally, that is, after the while loop’s condition has become false. Abnormal, premature termination, due to reasons such as a break or return statement, skips that code.

Basic Python whileelse Syntax

The whileelse syntax closely resembles the standard while loop, but with the addition of the else keyword followed by a colon : and a code block:

while condition:
    loop-block
else:
    else-block
  • while condition: The regular while loop condition.
  • loop-block: Code executed as long as the condition is true.
  • else-block: Code executed after the loop finishes normally, when the condition turns false.

Using the else Clause With while Loops

The while loop lesson introduced the code example below that prints out the Fibonacci sequence for integers smaller than 100.

Reminder: The Fiboncci sequence is an infinite sequence of integers in which the current number is always the sum of the previous two, assuming the first two integers are 1 and 1. It proceeds as follows: 1, 1, 2, 3, 5, 8, 13…

Example:

prev = 0
current = 1
while current < 100:
    print(current)
    prev, current = current, prev + current 

Output:

1
1
2
3
5
8
13
21
34
55
89

To explore the else clause of the while loop, Let’s give that example an additional twist. This time, instead of printing the sequence, the program will find and print the first Fibonacci number whose least-significant (right-most) two digits are 999.

There is one problem, however. It’s not entirely certain that such a number exists, or maybe it’s so large that looking for it will take too long. To resolve this, our program will use a while loop to put a limit on the size of the number checked. If the loop reaches that limit, it means the maximum has been reached without finding the number. Should that happen, we’d like to be informed with a “not found” message.

This requirement is perfect for an else clause because it enables something to happen when the loop goes through all its iterations. The next example show the implementation.

Example:

prev = 0
current = 1
max_number = 10**12

while current < max_number:
    if current % 1000 == 999:
        print(current)
        break
    prev, current = current, prev + current 
else:
    print("Not found.")

Output:

Not found.

The example above uses a while loop (line 5) to iterate over Fibonacci numbers until they become greater than a trillion. The loop condition checks that the current Fibonacci number is less than max_number, which is initialized on line 3 to a trillion. Line 6 checks whether the least-significant three digits of the Fibonacci number are 999 using the modulo (remainder upon division) % operator. If they are, then the number is printed and the loop terminates with a break on line 8. If executed, the break prevents the loop’s else clause from being used. If break doesn’t execute, it means the loop terminated normally, and the code inside the else is executed, printing “Not found” on line 11.

As the example demonstrates, there is no Fibonacci number smaller than a trillion that ends with 999. Let’s try our luck with one less digit and look for a Fibonacci number that ends with 99.

Example:

prev = 0
current = 1
max_number = 10**12

while current < max_number:
    if current % 100 == 99:
        print(current)
        break
    prev, current = current, prev + current 
else:
    print("Not found.")

Output:

32951280099

The example above is identical to the previous one except that it changes the check to 99 on line 6. It finds the Fibonacci number 32951280099 and prints it out right before breaking on line 8. The else clause is not executed and “Not found” is not printed.

Summary & Reference for the Python whileelse Clause

The Python whileelse clause is an optional addition to the while loop. It executes a code block after the loop, if it finishes normally, i.e., if the loop condition becomes false.


Abnormal, premature loop termination, due to reasons such as a break or return statement, skips that code.


Here is the basic whileelse syntax:

while condition:
    loop-block
else:
    else-block