For-loops in Python

What is the best way to do this in Python?

for (v = n / 2 - 1; v >= 0; v--)

At first I tried Google, but as far as I can see, the only solution would be to use while.

+5
source share
4 answers

The way to do this is with xrange():

for v in xrange(n // 2 - 1, -1, -1):

(Or, in Python 3.x, with range()instead xrange().) //Is a gender separation that ensures that the result is an integer.

+13
source

I would do this:

for i in reversed(range(n // 2)):
    # Your code
    pass

It’s a little clear that this is the reverse sequence, what is the lower limit and what is the upper limit.

+15
source
for v in range(n//2, -1, -1)

90% , for C/Java/#/VB, :

listOfStuff = [doSomethingWith(v) for v in range(n//2, -1, -1)]
+5
for v in xrange(n/2 - 1, 0, -1):
   #your code here

Where v and n are inteither treated as ints. This means that division will be a whole division, i.e. 1/2 == 0 is True.

Note. This is for Python 2.x.

-1
source

All Articles