- Complete Python Bootcamp: Go from zero to hero in Python
- Complete Python Web Course: Build 8 Python Web Apps
To repeat code, the for keyword can be used. To execute a line of code 10 times we can do:
for i in range(1,11): print(i)
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): print(i)
but will output 0 to 9.
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.
Loops can be combined:
for i in range(0,10): for j in range(0,10): print(i,' ',j)
In this case we have a multidimensional loops. It will iterate over the entire coordinate range (0,0) to (9,9)