Decrementing for loops

PythonFor LoopDecrement

Python Problem Overview


I want to have a for loop like so:

for counter in range(10,0):
       print counter,

and the output should be 10 9 8 7 6 5 4 3 2 1

Python Solutions


Solution 1 - Python

a = " ".join(str(i) for i in range(10, 0, -1))
print (a)

Solution 2 - Python

Check out the range documentation, you have to define a negative step:

>>> range(10, 0, -1)
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Solution 3 - Python

You need to give the range a -1 step

 for i in range(10,0,-1):
    print i

Solution 4 - Python

for i in range(10,0,-1):
    print i,

The range() function will include the first value and exclude the second.

Solution 5 - Python

range step should be -1

   for k in range(10,0,-1):
      print k

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpandoragamiView Question on Stackoverflow
Solution 1 - Pythonuser225312View Answer on Stackoverflow
Solution 2 - PythonAndiDogView Answer on Stackoverflow
Solution 3 - PythonNaviView Answer on Stackoverflow
Solution 4 - PythonPrithviJCView Answer on Stackoverflow
Solution 5 - PythonAysun ItaiView Answer on Stackoverflow