15. continue
statement¶
The continue
statement inside a for
loop jumps to the beginning of the loop and forces it to continue to the next item in the loop.
This statement is used to prevent the code inside the for loop that follows the continue
statement from executing.
Example that prints all numbers from 1 to 20, except multiples of 3:
for num in range(1, 21): # <----+
if num % 3 == 0: # |
continue # -----+
print(num)
1
2
4
5
7
8
10
11
13
14
16
17
19
20
Exercises¶
Write a program that prints all numbers from 1 to 20, except multiples of 5.
Write a program that prints all the numbers from 1 to 10 except 4 and 7.
Write a program that adds all numbers from 1 to 100, except multiples of 3. Use the continue statement. The result should be 3367.
Write a program that counts the number of numbers from 1 to 100 if we remove the multiples of 3 and the multiples of 7. The result should be 57.
Clue:
contador = 0 for num in range(1, 101): ...
Write a program that prints all non-leap years from 1600 to 2400.
Condition to know if a year is a leap year:
if ( (anio % 4 == 0) and (anio % 100 != 0 or anio % 400 == 0) ): # Año bisiesto
Write a program that changes all spaces ' ' in a sentence to the underslash symbol '_'.
Program that prints all the letters of a sentence:
frase = 'Hola, mundo. Me llamo Python y sé como hablar con la a.' for letra in frase: print(letra, sep='', end='')
Write a program that prints all the letters of a sentence by changing all the vowels to the letter 'a'.
Program that prints all the letters of a sentence:
frase = 'Hola, mundo! Me llamo Python y sé como hablar con la a.' for letra in frase: print(letra, sep='', end='')
Condition to know if a letter is a vowel:
if letra in 'aeiouAEIOUáéíóúÁÉÍÓÚ':