What is the best way of doing this in Python?
for (v = n / 2 - 1; v >= 0; v--)
I actually tried Google first, but as far as I can see the only solution would be to use while
.
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.
Similar to a While loop, a For loop consists of three parts: the keyword For that starts the loop, the condition being tested, and the EndFor keyword that terminates the loop.
Syntax of a For LoopThe initialization statement describes the starting point of the loop, where the loop variable is initialized with a starting value. A loop variable or counter is simply a variable that controls the flow of the loop. The test expression is the condition until when the loop is repeated.
I would do this:
for i in reversed(range(n // 2)):
# Your code
pass
It's a bit clearer that this is a reverse sequence, what the lower limit is, and what the upper limit is.
The way to do it is with xrange()
:
for v in xrange(n // 2 - 1, -1, -1):
(Or, in Python 3.x, with range()
instead of xrange()
.) //
is flooring division, which makes sure the result is a whole number.
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