Looping from 1 to infinity in Python

2020-01-27 03:58发布

In C, I would do this:

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

How can I achieve something similar in Python?

标签: python loops
11条回答
干净又极端
2楼-- · 2020-01-27 04:41

Using itertools.count:

import itertools
for i in itertools.count():
    if there_is_a_reason_to_break(i):
        break

In Python2 xrange() is limited to sys.maxint, which may be enough for most practical purposes:

import sys
for i in xrange(sys.maxint):
    if there_is_a_reason_to_break(i):
        break

In Python3, range() can go much higher, though not to infinity:

import sys
for i in range(sys.maxsize**10):  # you could go even higher if you really want
    if there_is_a_reason_to_break(i):
        break

So it's probably best to use count().

查看更多
不美不萌又怎样
3楼-- · 2020-01-27 04:42

If you need to specify your preferred step size (like with range) and you would prefer not to have to import an external package (like itertools),

def infn(start=0, step_size=1):
    """Infinitely generate ascending numbers"""
    while True:
        yield start
        start += step_size

for n in infn():
    print(n)
查看更多
叼着烟拽天下
4楼-- · 2020-01-27 04:44
a = 1
while a:
    if a == Thereisareasontobreak(a):
        break
    a += 1
查看更多
我欲成王,谁敢阻挡
5楼-- · 2020-01-27 04:48

Probably the best solution to this is to use a while loop: i=1 while True: if condition: break ...........rest code i+=1

查看更多
SAY GOODBYE
6楼-- · 2020-01-27 04:48
while 1==1:  
    if want_to_break==yes:  
       break  
    else:
       # whatever you want to loop to infinity  

This loop with go indefinitely.

查看更多
登录 后发表回答