While loops

Contents

While loops#

while loops repeat instructions until certain condition is False (while the condition is True). The syntax is as follows:

    while condition:
        # Some code to be executed repeatedly as long as condition is True
        
    # Some more code to be executed once the while loop is over, executed once

Some while loops are infinite, where the condition never becomes False. A while loop, like if statements, needs the code to be indented.

Example#

counter = 0  # Set counter
print("Initial counter is: ", counter)

print("Entering while loop")
while counter <= 10:
    # Increase counter by 1 as long as it is <= 10
    counter += 1
    
    print(counter)
    
print("While loop finished.")
print("Final counter is: ", counter)
Initial counter is:  0
Entering while loop
1
2
3
4
5
6
7
8
9
10
11
While loop finished.
Final counter is:  11

Exercises#


  • Write a program that prints all Fibonacci numbers smaller than 50. An example of a Fibonacci sequence is the following:

\[ F_0 = 0,\quad F_1 = 1, \quad F_{n}=F_{n-1}+F_{n-2}.\]

  • Create a while loop to find Celsius temperatures for Fahrenheit temperatures between 20\(^\circ\)F and 80\(^\circ\)F at 5\(^\circ\)F increments. The Fahrenheit-Celsius conversion formula is:

\[ T_{Celsius} = \frac{5}{9}*(T_{Fahrenheit}-32). \]