To decrement a for loop in Python, the easiest way is to use range() and pass “-1” as the third argument to step by -1 after each iteration.

for i in range(5,0,-1):
    print(i)

#Output:
5
4
3
2
1

When working in Python, the ability to loop over objects and perform an action multiple times efficiently is very important.

Using loops in our programs allows us to create complex operations.

One such case where you might need to do a little more work is if you want to go in reverse when looping. You can easily decrement in a for loop with the range() function.

By default, when you use range() in a for loop, you work sequentially from the beginning to the end in order. To go in reverse, we can pass a third argument to range() and decrement the index of the for loop.

To decrement a for loop in Python, the easiest way is to use range() and pass “-1” as the third argument to step by -1 after each iteration.

Below is a simple example which decrements a for loop in Python.

for i in range(5,0,-1):
    print(i)

#Output:
5
4
3
2
1

How to Decrement while Loop in Python

If you want to use a while loop instead of a for loop in your Python program, you just need to keep track of the index and subtract 1 from it after each iteration.

Below is a simple example of how you can decrement a while loop in Python.

i = 5

while i > 0:
    print(i)
    i = i - 1

#Output:
5
4
3
2
1

Hopefully this article has been useful for you to learn how to decrement a for loop in Python using range().

Categorized in:

Python,

Last Update: March 11, 2024