# 13. for statement¶

The for statement allows us to repeat a block of code several times while a variable is changing its value.

This block of code that is repeated several times is called a loop.

Example:

for num in range(1, 10):
print(num)

This example will print to the screen all the numbers from 1 to 9 (10 is not included in the range).

Example:

for nombre in ['Abel', 'Beatriz', 'Conchi', 'Diana', 'Elena', 'Francisco']:
print('Hola', nombre)

This example will print a greeting for all the names in the list, from 'Abel' to 'Elena'.

## Exercises¶

1. Write a program that prints the table of 6:

6 x 0 = 0
6 x 1 = 6
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
6 x 5 = 30
6 x 6 = 36
6 x 7 = 42
6 x 8 = 48
6 x 9 = 54
6 x 10 = 60

Clue:

for ...
print('6 x', b, '=', 6*b)

2. Write a program that asks for a number and then adds all the numbers between 1 and the entered number.

Example 1:

Introduce un número: 5
La suma de todos los números desde
el 1 hasta el 5 es igual a 15

Example 2:

Introduce un número: 27
La suma de todos los números desde
el 1 hasta el 27 es igual a 378

Clue:

suma = 0

for i in ...
suma = suma + i

print('La suma de todos los números desde')
print('el 1 hasta el', ... ,'es igual a', ... )

3. Write a program that asks for a number and then multiplies all the numbers between 1 and the entered number. This operation is called factorial.

Example 1:

Introduce un número: 3
El factorial de 3 es igual a 6

Example 2:

Introduce un número: 10
El factorial de 10 es igual a 3628800

4. Write a program that prints on the screen all the ages from 10 to 20 and, next to it, that prints if it is older or younger:

5. Write a program that asks for a number and then prints if it is divisible by any number between 2 and 20.

Example 1:

Introduce un número: 60

60 es divisible por 2
60 es divisible por 3
60 es divisible por 4
60 es divisible por 5
60 es divisible por 6
60 es divisible por 10
60 es divisible por 12
60 es divisible por 15
60 es divisible por 20

Example 2:

Introduce un número: 28

28 es divisible por 2
28 es divisible por 4
28 es divisible por 7
28 es divisible por 14

Note that a number 'num' is divisible by 5 if its remainder when divided by 5 equals zero:

if (num % 5 == 0):
print(num, ' es divisible por ', 5)

6. Write a program that prints all the numbers from 1 to 100. Numbers divisible by 3 must be replaced by the word 'choco'. Numbers divisible by 5 must be replaced by the word 'late'. Numbers divisible by 3 and 5 must be replaced by the word 'chocolate':

1
2
choco
4
late
choco
7
8
choco
late
11
choco
13
14
chocolate
16
.
.
.

Note that a number 'num' is divisible by 3 if its remainder when divided by 3 equals zero:

if (num % 3 == 0):
print(num, ' es divisible por 3')