Lets Count Backward ๐๐คจ
As one of the most popular languages of the 21st century, Python certainly has a lot of interesting functions worth exploring and studying in-depth. Today we would look at iteration of numbers which can be done by a couple of techniques in Python.
Lets us discuss the available options available.
Using the reversed() function
This function takes a single parameter and returns the reversed iterator of the sequence.
[5, 3, 4, 2, 1]
This function can also be applied to user-defined objects. However, not that the object must have already provided a `__len__()` and `__getitem__()` or an `__reversed__`.
['5', '4', '3', '2', '1']
The while loop
This requires using a counting variable inside of a while loop.
10
9
8
7
6
5
4
3
2
1
10
9
8
7
6
5
4
3
2
1
The for loop
As long as the condition is right, The for loop can also count backwards. We need to always be careful when using a for loop or we could end up with an infinite loop.
10
9
8
7
6
5
4
3
2
1
0
Here the range function takes three arguments: start, stop, step which is our 10, -1 and -1. Step being the difference between our current value and the previous.
10
9
8
7
6
5
4
3
2
1