This page will go through how to repeat a loop in python n times. This will be shown with both a For loop as well as a While loop.
Whilst looping is a great thing, and a first step in many languages. Please consider switching to matrix operations once the dataset gets a lot bigger as that will have a dramatic impact on performance when working with thousands, or millions of rows. For example 1 line of code to add a "column calculation" versus looping through the entire matrix.
Loops can be divided in to two types of loops: For Loops or While Loops. For Loops are definitely the ones I use the most. Whilst creating While loops can be a good thing, sometimes it can also get your code into an annoying endless circle as it is basically just a 'For loop' to infinity.
For Loops examples
Below we show a simple For loop that is repeated 10 times in two different ways since python's range syntax starts with 0.
# Looping 0 to 9, which is 10 times.
for x in range(10):
print(x)
The "Range" syntax above is useful for looping to a number or between certain numbers. In python, the first index is 0. which is recurring for many other python syntaxes. The range syntax works like the following.
class range(stop)
class range(start, stop[, step])
This means that we can use the second class option above to write the python statement so that our loop starts at 1 and goes to 10. Note that our first loop stopped at 9 so in order for our loop to stop and include 10 we need to change the stop number to 11 like below.
# Looping 1 to 10, which is 10 times.
for x in range(1,11):
print(x)
While Loop.
If we want to repeat a loop 10 times with a While syntax, we don't need to use the "Range syntax". We can simply use a variable "i" in this case for which we increase (or decrease for that matter) the value for each iteration.
# need to increment i with 1 for each loop.
# otherwise this loop will continue forever.
# increment of i could also have been written as i = i + 1.
i = 1
while i < 10:
print(i)
i += 1
Learn more about Python loops in my complete guide here:
Learn more about VBA here for all my posts: https://www.pls-fix-thx.com/vba
Learn more about Python here for all my posts: https://www.pls-fix-thx.com/python
If you have found this article or website helpful. Please show your support by visiting the shop below.