How To Count Down In a For Loop Python

How To Count Down In a For Loop Python | A loop is a basic tool of programming that allows us to execute some code till a given set of conditions returns true. It is a sequence of instructions that is continuously repeated until a certain condition is reached.

In Python, we can use the for loop to iterate over a sequence of elements. A for loop is used for iterating or repeating over a series or sequence(that is either a list, a tuple, a dictionary, a set, or a string). 

In this article, we will learn about counting down in for loop in Python programming language. Count down in for loop can be done using different methods. We will now discuss how to count down in a for loop in Python.

Using The Step Parameter to Count Down in a For Loop in Python

The increments between two consecutive numbers are specified using the step parameter in the range() function. We can count down in a for loop in Python using this step parameter.

For this, the start value should be more than the end value. The step parameter needs to have a negative value.

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

Output:-

7
6
5
4
3
2
1

Using the reversed() Function to Count Down in a for loop in Python

The reversed() function takes a series and reverses its order.

for i in reversed(range(1, 7)):
    print(i)

Output:-

6
5
4
3
2
1

Using the Slicing Technique to Count Down in a for loop in Python

Slicing refers to the process of extracting parts or portions from a sequence like a list, string, and more. We need to specify the starting and ending index within the brackets along with the step value if required. We can put this step value as -1.

for i in range(1, 8)[::-1]:
    print(i)

Output:-

7
6
5
4
3
2
1

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *