Date: 07/13/2023 :Author: Carlos Pardo Martín :License: Creative Commons Attribution-ShareAlike 4.0 International

16. break statement

The break statement inside a for loop jumps to the next statement outside the loop, stopping the loop from executing.

This statement 'breaks' the execution of the for loop.

Example that searches for the first number that is a multiple of 5 and 7. The program stops searching when it finds the first number that meets the condition:

for num in range(1, 100):
    if (num % 5 == 0) and (num % 7 == 0):
        print(num)
        break

You can also use the else statement in for loops. The block of code inside the else statement will be executed whenever the for loop terminates normally and will not be executed if the for loop terminates due to a break statement

Example:

for num in range(1, 100):
    if (num % 5 == 0) and (num % 7 == 0):
        print(num, 'es divisible por 5 y por 7')
        break
else:
    print('Ningún número es divisible por 5 y por 7')

Exercises

  1. Write a program that prints a countdown from 10 to 1 on the screen. The program should stop at the number 5.

  2. Write a program that asks for a password a maximum of 4 times. If the password is correct, you must write 'Authorized access' and finish. If the password is not correct all 4 times, you must write 'Unauthorized access'.

    The password and access validity must be written to a variable that will be checked at the end of the loop.

    Clue:

    password = 'secreto'
    
    for intento in range(4):
        entrada = input('Introduce la contraseña: ')
        ...
        ...
    else:
        ...
    
  3. Modify the following program so that it writes a sentence on the screen until it reaches letter number 30, where it must stop typing thanks to a break statement.

    It uses a letter counter to know when the loop should end.

    Clue:

    frase = 'En un lugar de la Mancha, de cuyo nombre no quiero acordarme'
    
    for letra in frase:
        print(letra, end='')
    
  4. Write a program that adds all the integers from 1 to 100 and that stops when the sum is greater than 1000. The program must indicate up to which number it has added and what the result of the addition is.

    Clue:

    suma = 0
    maximo = 1000
    
    for num in range(1, 101):
        ...
    
  5. Write a program that checks if a number has divisors between 2 and 1000. If it does have divisors, write to the screen that it is not a prime number. Otherwise write that it is a prime number.

    Clue:

    num = int( input('Escribe un número: ') )
    
    for divisor in range(2, 1001):
        if num % divisor == 0:
            ...
            ...
    else:
            ...