This page will go through how to reverse a loop in python for a given range 1 to 10 for example. The loop will in other words go backwards rather than the commonly increasing iteration for both a For loop syntax as well as a While loop syntax.
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.
Reverse Looping
For the "For" loop example we are reverse looping with the help of the Range syntax. The "Range" syntax is useful for looping to a number or between certain numbers as well as skipping numbers or, in our case going backwards with the help of the step parameter.
class range(stop)
class range(start, stop[, step])
# Looping 10 to 2. 9 times as last number is 2.
for x in range(10,1,-1):
print(x)
# Looping 10 to 1. 10 times as last number is 1.
for x in range(10,0,-1):
print(x)
While Loop.
If we want to range reverse from 10 to 1 in python with the "While syntax" we can simply use a variable "i" in this case for which we decrease its value for each iteration.
# need to decrease i with 1 for each loop.
# decrease of i could also have been written as i = i - 1.
i = 10
while i > 0:
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.
Comments