python暂停无限循环,用于执行代码外部循环

时间:2018-04-19 14:36:05

标签: python

我想知道这是否可行。我希望有一个无限的while循环,但仍然不会在while循环之外的其余代码继续运行,而循环打开。比如在每次迭代后打破while循环的方法。我需要找到一种方法来执行第二个print语句而不会完全打破while循环。

while True:
   print('i will loop forever')

print('this code will never be executed because of the while loop')

1 个答案:

答案 0 :(得分:1)

有很多方法可以实现这一点,例如线程。但是,看起来您可能希望连续循环一段时间,中断,然后继续。发电机在这方面表现优异。

例如:

def some_loop():
  i=0
  while True:
    yield i
    i+=1

my_loop=some_loop()

#loop for a while
for i in range(20):
  print(next(my_loop))

#do other stuff
do_other_stuff()

#loop some more, picking up where we left off
for i in range(10):
  print(next(my_loop))