I am trying to loop from 100 to 0. How do I do this in Python?
for i in range (100,0)
doesn't work.
I am trying to loop from 100 to 0. How do I do this in Python?
for i in range (100,0)
doesn't work.
Try range(100,-1,-1)
, the 3rd argument being the increment to use.
for i in range(100, -1, -1)
and some slightly longer (and slower) solution:
for i in reversed(range(101))
for i in range(101)[::-1]
In my opinion, this is the most readable:
for i in reversed(xrange(101)):
print i,
Generally in Python, you can use negative indices to start from the back:
numbers = [10, 20, 30, 40, 50]
for i in xrange(len(numbers)):
print numbers[-i - 1]
Result:
50
40
30
20
10