We can also loop in reverse using the range(start, end, step) function by giving the step argument a negative value. For example:
for i in range(7, 2, -1):
print(i)
The output of this code is:
7
6
5
4
3
Let's break down this code:
start = 7, so we start iterating from number 7.stop = 2, so we end at number 2. Notice it's still exclusively and we don't print 2.step = -1, so we decrease our number by 1 every time.
Assignment
Let's print all numbers from 5 through -5 in decreasing order.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
