Tags
python
Asked 3 years ago
6 Aug 2021
Views 435
Dock

Dock posted

Decreasing for loops in Python is possible ?

i am using more general purpose but i am giving simple example to show my problem

for n in range(12,0):
    print(n)

it print nothing so i got that range coming empty
so i debug more about it

print(list(range(12,0)))

it will print empty list []

so what i should do to run Decreasing for loop in Python ?
shyam

shyam
answered Aug 6 '21 00:00

generate range up to 12 by range(12) and reverse it by reversed() function


for n in reversed(range(12)):
    print(n)


it will generate the following output :

12
11
10
9
8
7
6
5
4
3
2
1
0
angeo

angeo
answered Aug 6 '21 00:00

range(start,stop,step) function can have three argument .
step is default value is 1 if you don't pass anything at third parameter then it takes 1 as step increment from start to stop
so in your case, you when you pass start and stop value which is start>stop and it never generates any range because 1 increment
but if we change step to -1, it will generate range for start>stop

so i use range(12,0,-1) which generate reverse range.

for n in range(12,0,-1):
    print(n)


it will print

12
11
10
9
8
7
6
5
4
3
2
1

Post Answer