Keywords: for loop, counting loop, loops
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 code 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 below a flow chart of 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.
The for loop works in a similar way as the while loop that we described in the previous article. If we illustrate the for loop using a flow chart, we get:
What the figure shows is that:
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):
for i in range(value):
code executed within the for loop
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)
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
Please leave feedback and help us continue to make our site better.
How useful was this article?
We are sorry that this post was not useful for you!
Let us improve this post!
Tell us how we can improve this post?
The for loop in Python is a so-called counting loop that repeats a code sequence a predetermined number of times. Hence, the for loop is best suited when you know the number of iterations that the loop will need to do
for i in range(value):
code executed within the for loop