While Loop
In programing, loops allow you to execute instructions repetitively. The while loop will repeat the instructions while a certain condition is true.
The syntax of the while
is the following:
The typical framework for a while statement often contains those 4 parts: initialisation, condition, processing & change.
with :
- an initialisation part where you initialise all the variables that you will be needing for your while;
- the condition part which will define if we execute the instructions in the body of the while;
- the processing part in the body of the while;
- the change part at the end of the while body that will modify the variables used in the condition of your while.
The while loop will usually be used for two reasons:
- Processing until a certain condition is checked.
n = "first value"
while "n is not equal to the value to stop"
processing
n = "new value"
- Reading a sequence of data
Examples
This code initialise two variables, n and i (initialisation). Then it checks if i is smaller than n (condition), if it is, it prints the value of the variable i (processing) and it adds 1 to i (change).
n = "yes"
while n == "yes":
print("This is my game.")
print("My game is now over.")
n = input("Do you want to play again? (yes/no)")
This code initialise one variable n to "yes" (initialisation). Then it checks if n is equal to "yes" (condition), if it is, it prints two messages (processing) and it asks if the user wants to play again (change).
total = 0
x = input("Give me a number or write stop: ")
while x != "stop":
total += int(x)
x = input("Give me a number or write stop: ")
print(total)
This code adds together the numbers given by the user and then prints the result. It first initialises the variable total and the variable x (initialisation). If there is not the word "stop" in the variable x, it adds the number to the variable total (processing). Then, it asks for another number (change). Once the user writes "stop", it prints the result.
Warning
- The print is only executed once at the end because it is not indented so it is not part of the while.
- You don't know if you will receive an integer or a string after your input so you first assume that it is going to be a string, and if it is not, you can convert it to an integer afterwards by writing int(x).