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}.\]
Answer
first = 0
second = 1
print(first)
while second <= 50:
print(second)
temp = first + second
first = second
second = temp
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). \]
Answer
temp_F = 20 # Initial temperature in Fahrenheit
dF = 5 # Increment in Fahrenheit
while temp_F <= 80:
temp_C = 5./9.*(temp_F-32) # Calculate the temperature in Celsius
# A nicely formatted f-string
print(f"{temp_F:.2f} degrees Fahrenheit is {temp_C:.2f} degrees Celsius.")
# Add increment to the temperature for the next iteration
temp_F = temp_F + dF