16. break
statement¶
The break
statement inside a for
jumps out of the loop to continue to the next statement after the loop.
This statement 'breaks' the execution of the for
loop.
En el siguiente ejemplo un contador desde el número 1 hasta el número 9 se rompe en el número 5:
for num in range(1, 10):
print(num)
if num == 5:
break
print('Final')
La salida por pantalla del anterior código será la siguiente:
1
2
3
4
5
Final
In this other example, a program looks for the first number that is a multiple of 5 and 7 among the first 100 numbers. The program stops searching when it finds the first number that meets the condition:
for num in range(1, 101):
if (num % 5 == 0) and (num % 7 == 0):
break
print(num)
La salida por pantalla del anterior código será la siguiente:
35
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('No encontrado ningún número divisible por 5 y por 7')
El ejemplo dará como resultado el número 35, pero si reducimos el rango
a range(1, 30)
el resultado nos dirá que no ha encontrado ningún
número divisible por 5 y por 7.
Exercises¶
Write a program that prints a countdown from 10 to 1 on the screen. The program should stop at the number 5.
Clue:
for num in range(10, 0, -1): ... ... ...
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 = '1234' for intento in range(4): entrada = input('Introduce la contraseña: ') ... ... else: print('Acceso no permitido')
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' contador = 0 for letra in frase: print(letra, end='') ... ... ...
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): suma = suma + num ... ... ...
Write a program that checks if a number has divisors between 2 and the number itself minus one. If you have a divisor, write on the screen that it is not a prime number. Otherwise write that it is a prime number.
Clue:
num = input('Escribe un número: ') num = int(num) for divisor in range(2, num): if num % divisor == 0: ... ... else: print(...)