The Python while Loop

Introduction

Like the for loop, the Python while loop is another way to repeat a block of code. The difference between the for loop and the while loop is that the for loop iterates through each item it obtains from an iterable object, whereas the while loop keeps iterating and executing its code block as long as a certain condition remains true.

Basic Python while Loop Syntax

The Python while loop consists of the while keyword, followed by a condition, and a colon :. The code block, which is indented below the while statement, will execute repeatedly as long as the specified condition remains true.

Like in the for loop, indentation is crucial for the correct execution of the code within the while loop. Python relies on indentation to determine the scope of code blocks.

Here’s the syntax of the basic while loop:

while condition:
    loop-block
  • condition: A Boolean expression that determines whether the loop should continue or terminate. The loop will continue as long as this condition evaluates to True.
  • loop-block: The code that will execute repeatedly as long as the condition is true. This code block is also called the body of the loop.

The following example uses a while loop to print the Fibonacci sequence.

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

The above example prints the Fibonacci sequence for integers that are smaller than 100. The loop condition current < 100 keeps the loop running until the number in the sequence reaches 100 or above, at which point it terminates the loop. After the number is printed on line 4, the compound variable assignment on line 5 prepares everything for the next iteration. It calculates the subsequent number in the sequence (`rev + current) and assigns it to current; it also saves the old value of current back prev.

Note that it is important to have the body of the loop alter the condition in some way so that it eventually becomes false, allowing the loop to terminate. (The previous example accomplishes this by calculating the new number in the Fiboncci sequence and assigning it to the variable current.) Otherwise, the loop will keep going forever, preventing the rest of the program from executing.

while Loops vs. for Loops

With a while loop, you can implement any looping logic possible in programming. Consequently, while loops can be used anywhere loops are needed. However, programmers mostly don’t use them and utilize for loops instead. The reason is that for loops are designed to provide, easy-to-use syntax for most kinds of looping needs.

for loops are good at iterating and doing something with every item in a collection, or some other predetermined sequence of items, such as integers in a range. For example, the following code prints every item in a list of planets.

planets = ["Mercury", "Venus", "Earth", "Mars", "Saturn", "Jupiter", "Uranus", "Neptune"]

for planet in planets:
    print(planet)
Mercury
Venus
Earth
Mars
Saturn
Jupiter
Uranus
Neptune

The code in the example above iterates through the planets list and prints all planet names using just two lines of for-loop code. The planet loop variable receives each of the items in planets one by one, as is done by the for loop construct automatically.

Now let’s see how the same program can be implemented with a while loop.

planets = ["Mercury", "Venus", "Earth", "Mars", "Saturn", "Jupiter", "Uranus", "Neptune"]

i = 0
while index < len(planets):
    print(planets[i])
    i += 1

The example above has the same output as the previous code example, which used a for loop to print the planets.

However, using the while loop, we have to do these following extra things, the for loop does for us:

  • Initialized the index variable with the code i = 0 on line 3.
  • Test that the index is still within bounds with the condition index < len(planets) on line 4.
  • Access the list item using the index with the code planets[i] on line 5.
  • Increment the index with i += 1 on line 6.

Using the `while` loop, there is much more work that needs to be done. In this, case the for loop shines.

The while loop on the other hand, is great to use when there is no existing collection of items or predefined sequence to iterate over. The first example above is such a case. Here it is again:

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

As you recall, the example calculates and prints the Fibonacci sequence (1, 1, 2, 3, 5, 8, 13…) up to, but not including the integer 100. There is no predefined sequence because we are using this very loop to calculate the sequence. Additionally, we don’t know the position in the sequence of the first Fibonacci number >= 100, and therefore, we can’t use a for loop with a range (as in for x in range(10)).

To summarize this section, use a for loop to iterate over items in a collection, or some other predetermined sequence, such as integers in a range, and use a while loop to iterate when there is no existing collection of items or predefined sequence to iterate over.

Infinite while Loop

An infinite loop is a loop that will continue running forever, and the while loop will do so if its condition remains true. It is useful to set up a while loop to run this way if it is terminated in an external way.

This can be done with the Python break statement that, when issued, will terminate a loop regardless of its condition.

Example:

while True:
    user_input = input("Enter a number (or 'exit' to quit): ")
    
    if user_input.lower() == 'exit':
        break

    number = int(user_input)
    square = number ** 2
    print(f"The square of {number} is {square}.")
    
print("Goodbye.")

Output:

Enter a number (or 'exit' to quit): > 2
The square of 2 is 4.
Enter a number (or 'exit' to quit): > 10
The square of 10 is 100.
Enter a number (or 'exit' to quit): 

The example above is a program for squaring numbers inputted by the user. The loop condition is the literal True, and will therefore never turn false. The loop continues until the user enters the word ‘exit’ at the prompt, at which point the break statement is executed, terminating the loop. “Goodbye” is printed at the end.

Summary & Reference for the Python while Loop

The while loop is a construct for repeating a block of code as long as a specified condition is true.


Its basic syntax uses the while keyword and a condition:

while condition:
    loop-block

Here is an example that prints reciprocals of positive integers down to a threshold using a while loop:

threshold = 0.07
x = 1
while 1/x >= threshold:
    print(f"The fraction 1/{x} is {1/x}.")
    x += 1

Use a while loop to iterate when there is no existing collection of items or predefined sequence to iterate over, and use a for loop to iterate over items in a collection, or some other predetermined sequence, such as integers in a range.


It’s possible to create a while loop that does not terminate due to its condition, which alwaasy remains true. It can be terminated externally with the break statement.

while True:
    user_input = input("Enter a number (or 'exit' to quit): ")
    
    if user_input.lower() == 'exit':
        break

    number = int(user_input)
    square = number ** 2
    print(f"The square of {number} is {square}.")
    
print("Goodbye.")