Do you want to repeat code blocks?

To repeat code, the for keyword can be used.

Sometimes you need to execute a block of code more than once, for loops solve that problem. We specify the start and end of the loop using the function range(min,max).

Related Course:

python for loop example code

To execute a line of code 10 times we can do:

for i in range(1,11):

The last number (11) is not included. This will output the numbers 1 to 10. Python itself starts counting from 0, so this code will also work:
for i in range(0,10):

but will output 0 to 9.

Illustrated in this graphic:

for loop control flow graph in python

The code is repeated while the condition is True. In this case the condition is: i < 10. Every iteration (round), the variable i is updated.

Nested loops

Loops can be combined:

for i in range(0,10):
for j in range(0,10):
print(i,' ',j)
In this case we have multidimensional loops. It will iterate over the entire coordinate range (0,0) to (9,9)

 Download exercises