Python programming language is extensively used due to its clean and easy-to-understand syntax. Executing iteration a certain number of times is a common programming task.
Using loops in Python, particularly the for loop, allows programmers to iterate a block of code several times. This tutorial will guide you on how to perform a loop a specific number of times in Python.
Using the for Loop
The for loop in Python is commonly used for iterating over a sequence like lists, tuples, dictionaries, strings, or a range of numbers. Here is a simple way how you can loop a certain number of times:
1 2 |
for i in range(5): print(i) |
In the above example, range(5) generates a sequence of numbers from 0 up to 4, and for each number i in this range, the print function will be executed.
Understanding the range() function
Range() is a built-in function of Python that is used to generate a sequence of numbers. If given one parameter, range() generates numbers from 0 to the specified number. If given two parameters, range() generates numbers from the first given number up to the second given number.
Finally, if given three parameters, range() generates numbers from the first number up to the second number with a step size defined by the third parameter.
1 2 |
for i in range(0, 10, 2): print(i) |
In this code, numbers from 0 to 8 with a step size of 2 are generated, printing even numbers from 0 to 8.
Looping in Reverse Order
You may want to loop in reverse order which can be done using the reversed() function:
1 2 |
for i in reversed(range(5)): print(i) |
In this example, the reversed() function is used to reverse the sequence generated by range(5).
Full code
1 2 3 4 5 6 7 8 |
for i in range(5): print(i) for i in range(0, 10, 2): print(i) for i in reversed(range(5)): print(i) |
Output
0 1 2 3 4 0 2 4 6 8 4 3 2 1 0
Conclusion
Python offers the for loop to iterate a block of code a definite number of times. The flexibility of performing actions a specific number of times, with the possibility of controlling the start and stop points of the loop, as well as the step size, is a powerful feature. With the range() function and the reversed() function, you have numerous methods to control your loop operations.