Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decrementing for loops [duplicate]

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

like image 351
pandoragami Avatar asked Jan 22 '11 10:01

pandoragami


People also ask

Is decrementing faster than incrementing?

Increment is always faster than decrement.

How do you decrement a loop?

For decrementing the For loop, we use the step value as a negative integer. In the above example, the starting point is set as a higher limit and the endpoint as a lower limit, and a negative step value for decrementing for the loop. We can also decrement a While loop.

Can you increment i in a for loop?

A for loop doesn't increment anything. Your code used in the for statement does. It's entirely up to you how/if/where/when you want to modify i or any other variable for that matter.

How do you decrement a for loop in Java?

The increment operator increments the value of the operand by 1 and the decrement operator decrements the value of the operand by 1. We use these operators to increment or, decrement the values of the loop after executing the statements on a value.


5 Answers

a = " ".join(str(i) for i in range(10, 0, -1))
print (a)
like image 54
user225312 Avatar answered Oct 02 '22 20:10

user225312


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]
like image 31
AndiDog Avatar answered Oct 02 '22 18:10

AndiDog


You need to give the range a -1 step

 for i in range(10,0,-1):
    print i
like image 26
Navi Avatar answered Oct 02 '22 20:10

Navi


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

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

like image 22
PrithviJC Avatar answered Oct 02 '22 19:10

PrithviJC


range step should be -1

   for k in range(10,0,-1):
      print k
like image 32
Aysun Itai Avatar answered Oct 02 '22 18:10

Aysun Itai