18. while statement

The while statement allows a block of code to be executed multiple times while a condition is met.

It is a type of loop with condition. It is used when we do not know exactly how many times a block of code needs to be executed, but we do know what condition must be met.

Example of a program that adds prices while the total is less than 1000:

suma = 0

while suma < 1000:
    precio = input('Introduce un precio: ')
    suma = suma + int(precio)

print('La suma de todos los precios es mayor de 1000')

while True statement

You can also use the while statement with an always true condition to make a loop that runs forever:

while True:
    print('Hola, mundo!')

In order to stop the operation of this program, you must press the [Control] + [C] keys.

The previous program is not very functional because it does not have a condition to stop. Now we will see another example with the while statement that is stopped thanks to a break statement after writing the word 'end':

while True:
    nombre = input('Escribe tu nombre: ')
    if nombre == 'fin':
        break
    print('Hola', nombre)

This construction is equivalent to saying to execute a block of statements until a condition is met.

Exercises

  1. Write a program with the while statement that prints all the numbers from 0 to 10.

    Clue:

    contador = 0
    while ... :
        ...
        contador = contador + 1
    
  2. Modify the previous program so that it prints all numbers from 10 to 0.

  3. Write a program that adds all the integers starting from 1 and stops when the sum is greater than or equal to 1000.

    At the end you must write from what number to what number you have added and how much the sum is worth.

    Clue:

    suma = 0
    contador = 1
    while ... :
        ...
    
  4. Write a program that repeats continuously until the letter 'n' is entered on the keyboard to the question 'Do you want to continue? (Y/n)'.

    Clue:

    while True:
        respuesta = input( ... )
    
  5. Write a program that prints the Fibonacci sequence up to the number 1000.

    Clue:

    a = 0
    b = 1
    while ... :
        print(b)
        suma = a + b
        a = b
        b = suma
    
  6. Write a program that plays a number guessing game with the user. If the number entered is higher than the secret number, it must print a hint saying 'Too high'. You should also print a 'Too Low' hint for numbers smaller than the secret number.

    When the user guesses the secret number, the program should print 'You guessed right' and stop.

    Clue:

    import random
    numero_secreto = random.randint(1, 100)
    
    while True:
        ...