When we want to print reverse order of number using loops, for eg: 1 to 10 in reverse, we write the syntax as (10,0,-1), why don't we write it as (1,11,-1)? Doesn't -1 already mean reverse, so why do we write 10,0 instead of 1,11 for range?
The arguments for range
in python are range(start, stop, step)
.
The start
value is the first index (inclusive) of the range function. This defaults to 0. In your case, the start value is 10.
The stop
value is the last index (exclusive) of the range function. This means that the index before this number will be the last number.
The step
value is the change in index between each run. This defaults to 1
, but in your case is -1
.
This means that the order of execution in your example would be:
10 -> Start
9 -> Step (-1)
8 -> Step (-1)
7 -> Step (-1)
6 -> Step (-1)
5 -> Step (-1)
4 -> Step (-1)
3 -> Step (-1)
2 -> Step (-1)
1 -> Step (-1), Stop as next index would be 0
Because Python reads your loop from the first argument until the last one. When you call:
for _ in range(10, 0, -1):
Python reads exactly like that:
Otherwise, your loop won`t do anything.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.