Two Simple Ways to Count Backwards in Python
Learn to use the range() function
There are a variety of reasons to count backwards in a program. Maybe you want to iterate over a list starting from the end or simply want to display a countdown timer.
We have multiple options available to us and are going to introduce two of those options: manually modifying a counter variable and using the range() function.
Manually Counting
The most basic method of counting backwards is to use a counting variable inside of a while loop. We need three definitions in order to count backwards: the starting point, how to exit the loop, and how to modify the loop.
Let’s set up a countdown timer from 10 to 0. We identify that the counter starts at 10, exits at 0, and the counter will be reduced by one after each loop.count = 10while count > 0:
print(count)
count = count - 1
A manual counter will always provide the highest level of flexibility; however, when the counter is straightforward then we can use more refined iteration techniques to count backwards.
Using the range() Function
Alternatively, when our backwards count has a known start and end as well as a common increment — called a step value — then we can use the range() function and a for loop.
We’ll set up the exact same countdown timer using range() and we’ll see immediately how much cleaner the code is.for count in range(10,0,-1):
print count
In this example, the range() function takes three arguments: start, stop, step. If we wanted to reduce our count by two each iteration, then we would set the step to -2. Also, be careful not to mix up the start and stop. You’ll end up with an infinite loop.
What is your favorite way to count backwards? Share your experiences, questions, and feedback below. Thank you for reading and consider following Code 85 for more plain language programming guides.