Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

While loops

Learning outcomes

Prerequisites

While loop syntax

With for loops, we learned how to repeat an operation for a pre-determined amount of iterations. However, in some circumstances, we may want to keep repeating until certain conditions are met. The solution for this, is the while loop. Here is the generic syntax:

while condition:
    some action

For example:

n_protons = 1

while n_protons < 6:
    print(f"The number of protons is {n_protons}.")
    n_protons = n_protons + 1 # add 1 to n_proton

Note how the number 6 never appears because as soon as n_protons becomes 6, the condition is not fulfilled and the while loop stops. Exchange the order of the last two lines. Check the output and ensure that it makes sense.

This example showed how small errors can accidentally cause infinite loops, which keep your computer busy until they are solved. while loops are the primary cause of infinite loops in programming, but thankfully most problems can be resolved with a safer for loop in Python.

Solution

This is a hard task but a classic exercise for beginner programmers.

# initiate Fibonacci sequence
fibo_old = 0 # penultimate number
fibo_new = 1 # current final number

# set ending condition
while fibo_new < 1000:
    # calculate the new number
    new_sum = fibo_new + fibo_old
    # update the penultimate number
    fibo_old = fibo_new
    # update the new final number
    fibo_new = new_sum
    print(fibo_new)

This is an example of a task that is more at home in a while loop than a for loop. We can’t expect to know how long the loop will be (or we’d already know the answer), so while is our best bet. It’s possible to construe a for loop with a careful break statement to achieve the same task, but it would be longer to write and less clear to read.

If you want to challenge yourself, add an if statement so that only the odd Fibonacci numbers are printed.

Summary