newbie question

Jeff Shannon jeff at ccvcorp.com
Wed Feb 9 21:10:40 EST 2005


doodle4 at gmail.com wrote:

> Thanks for the reply.
> 
> I am trying to convert some C code to python and i was not sure what
> the equivalent python code would be.
> 
> I want to postdecrement the value in the while loop. Since i cannot use
> assignment in while statements is there any other way to do it in
> python?

Roughly speaking, if you have a loop in C like

while (n--) {
     func(n);
}

then the mechanical translation to Python would look like this:

while True:
     n -= 1
     if not n:
         break
     func(n)

However, odds are fairly decent that a mechanical translation is not 
the best approach, and you may (as just one of many examples) be much 
better off with something more like:

for i in range(n)[::-1]:
     func(n)

The '[::-1]' iterates over the range in a reverse (decreasing) 
direction; this may or may not be necessary depending on the 
circumstances.

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list