Count down in a for loop in Python

[ad_1]

How to count down in a for loop in Python?

A loop is a basic tool of programming that allows us to execute some code till a given set of conditions returns True. The for loop is one such loop available in many programming languages.

In Python, we can use the for loop to iterate over a sequence of elements. Such a sequence can be a list, a tuple, and many more. The for loop can iterate over such sequences till its end is reached. The range() function returns such a sequence (In Python 2, the range() function directly returns a list of elements).

It returns a sequence of numbers from the given range. The range can be provided within the function using the start, stop, and step parameters. The start and stop parameters define the endpoints of the sequence. The increment between successive numbers is determined by the step parameter.

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

As discussed, the increment between two successive numbers is determined using the step parameter in the range() function. We can count down in a for loop in Python using this.

For this, the start value should be greater than the end value. The step parameter needs to have a negative value. To count down by one, we can specify this parameter as -1. Essentially, we will traverse through a sequence that is in reverse order.

See the code below.

Output:

5
4
3
2
1

In the above example, we count down from 5 to 0 using the for loop. This is the most efficient and fast method to count down in a for loop in Python.

[ad_2]

Leave a Comment