Looping from 1 to infinity in Python

前端 未结 6 2181
日久生厌
日久生厌 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:18

    Simplest and best:

    i = 0
    while not there_is_reason_to_break(i):
        # some code here
        i += 1
    

    It may be tempting to choose the closest analogy to the C code possible in Python:

    from itertools import count
    
    for i in count():
        if thereIsAReasonToBreak(i):
            break
    

    But beware, modifying i will not affect the flow of the loop as it would in C. Therefore, using a while loop is actually a more appropriate choice for porting that C code to Python.

提交回复
热议问题