【问题标题】:Return from a while loop without exiting it python [duplicate]从while循环返回而不退出它python [重复]
【发布时间】:2019-11-06 23:11:51
【问题描述】:

我知道这是不可能的。 Return 将退出它。有没有办法让它成为可能。我有while循环,它计算值。我想从 while 循环中返回值并将其用于进一步处理并再次返回到 while 循环并继续它停止的地方。我知道返回将退出循环。如何让它成为可能。

示例代码如下:

import datetime
import time
def fun2(a):
    print("count:", a)
def fun():
    count = 0
    while 1:
        count = count+1
        time.sleep(1)
        print(count)
        if count == 5:
            return count
a = fun()
fun2(a)

我的输出:

1
2
3
4
5
count: 5

所需输出:

1
2
3
4
5
count: 5
6
7
8
9
and goes on....

【问题讨论】:

  • 使用generator
  • 其实yield而不是return

标签: python python-3.x for-loop while-loop


【解决方案1】:

看来您需要generator。在调用next 时,生成器将记住该值和yield,当它可以被5 整除时(我通过查看您的输出假设),并且会记住旧状态,直到您再次调用next。另请注意,这是一个无限生成器。

def fun():
    count = 0
    while True:
        count = count+1
        print('inside fun', count)
        if count % 5 == 0:
            yield count

f = fun()
print(next(f))
print(next(f))

输出将是

inside fun 1
inside fun 2
inside fun 3
inside fun 4
inside fun 5
5
inside fun 6
inside fun 7
inside fun 8
inside fun 9
inside fun 10
10

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-15
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 2013-05-15
    相关资源
    最近更新 更多