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
Increment is always faster than decrement.
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.
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.
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.
a = " ".join(str(i) for i in range(10, 0, -1))
print (a)
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]
You need to give the range a -1 step
for i in range(10,0,-1):
print i
for i in range(10,0,-1):
print i,
The range() function will include the first value and exclude the second.
range step should be -1
for k in range(10,0,-1):
print k
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With