Looping from 1 to infinity in Python

前端 未结 6 2196
日久生厌
日久生厌 2020-11-27 18:41

In C, I would do this:

int i;
for (i = 0;; i++)
  if (thereIsAReasonToBreak(i))
    break;

How can I achieve something similar in Python?

6条回答
  •  感动是毒
    2020-11-27 19:10

    If you're doing that in C, then your judgement there is as cloudy as it would be in Python :-)

    For a loop that exits on a simple condition check at the start of each iteration, it's more usual (and clearer, in my opinion) to just do that in the looping construct itself. In other words, something like (if you need i after loop end):

    int i = 0;
    while (! thereIsAReasonToBreak(i)) {
        // do something
        i++;
    }
    

    or (if i can be scoped to just the loop):

    for (int i = 0; ! thereIsAReasonToBreak(i); ++i) {
        // do something
    }
    

    That would translate to the Python equivalent:

    i = 0
    while not there_is_a_reason_to_break(i):
        # do something
        i += 1
    

    Only if you need to exit in the middle of the loop somewhere (or if your condition is complex enough that it would render your looping statement far less readable) would you need to worry about breaking.

    When your potential exit is a simple one at the start of the loop (as it appears to be here), it's usually better to encode the exit into the loop itself.

提交回复
热议问题