The for loop in Python is used when you want an operation to be repeated a specific number of times. Thanks to the for loop, you do not have to program the same thing several times because you can reuse the same code several times instead.
The for loop in Python is used to iterate (repeat) part of the program several times. If the number of iterations (repetitions) is a fixed number, it is recommended to use the for loop.
The image to the right shows a flow chart for how the for loop works. If the condition is met (Yes) then the operation is performed, if the condition is not met (No) then the program moves on.
After the operation is performed, the given initial value is increased and the loop then repeats the process and returns and checks if the condition is met.
for i in range(value): should happen inside the loop
The for loop is easily declare through the reserved word for. The for loop in the simplest form is done by specifying how many times you want the loop to be executed. This can be done with the command into in range (value):
Let’s take a simple example of how we can use the for loop to perform an operation a given number of times.
for i in range(5): print("Counter:", i)
In this example, the process will be executed 5 times, since it is the value specified in range (). The good thing about the for loop is that the value of the variable in, automatically increases after each iteration.
The result in this case becomes:
Counter: 0 Counter: 1 Counter: 2 Counter: 3 Counter: 4
So we have in a simple and fast way written a program that prints a value 5 times with the help of a loop, which is much easier than printing five times (although the result would be the same). But what if you wanted to print a value 100 times? Or maybe 1000?
For more technical and specific information about the for loop we recommend the Python docs website