In C, I would do this:
int i;
for (i = 0;; i++)
if (thereIsAReasonToBreak(i))
break;
How can I achieve something similar in Python?
In C, I would do this:
int i;
for (i = 0;; i++)
if (thereIsAReasonToBreak(i))
break;
How can I achieve something similar in Python?
Reiterating thg435's comment:
Or perhaps more concisely:
takewhile
imitates a "well-behaved" C for loop: you have a continuation condition, but you have a generator instead of an arbitrary expression. There are things you can do in a C for loop that are "badly behaved", such as modifyingi
in the loop body. It's possible to imitate those too usingtakewhile
, if the generator is a closure over some local variablei
that you then mess with. In a way, defining that closure makes it especially obvious that you're doing something potentially confusing with your control structure.Simplest and best:
It may be tempting to choose the closest analogy to the C code possible in Python:
But beware, modifying
i
will not effect the flow of the loop as it would in C. Therefore, using awhile
loop is actually a more appropriate choice for porting that C code to Python.If you're doing that in C, then your judgement there is as cloudy as it would be in Python :-)
The better C way would be:
or:
That would translate to the Python:
Only if you need to exit in the middle of the loop somewhere would you need to worry about breaking. If your potential exit is at the start of the loop (as it appears to be here), it's usually better to encode the exit into the loop itself.
You can also do the following way:
This will result in an infinite
for loop
.