Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For-loops in Python

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.

like image 350
Znarkus Avatar asked Apr 12 '10 21:04

Znarkus


People also ask

What is a for loop in Python?

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.

What are the 3 parts of a for loop in Python?

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.

What is for loop and its syntax?

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.


2 Answers

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.

like image 163
hughdbrown Avatar answered Oct 20 '22 18:10

hughdbrown


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.

like image 45
Thomas Wouters Avatar answered Oct 20 '22 19:10

Thomas Wouters