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:

🐍 Python Script
while conditions:
    instructions
where the condition is a boolean expression and the instructions are indented.

The typical framework for a while statement often contains those 4 parts: initialisation, condition, processing & change.

🐍 Python Script
initialisation
while 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.
🐍 Python Script
n = "first value"
while "n is not equal to the value to stop"
    processing
    n = "new value"
  • Reading a sequence of data
🐍 Python Script
x = input('First data: ')
while x != 'F':
    processing
    x = input('Next data: ')

Examples

🐍 Python Script
n = 5
i = 0
while i < n:
    print(i)
    i += 1

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).

🐍 Python Script
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).

🐍 Python Script
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).