Bar*_*sen 6 python generator break while-loop conditional-statements
我刚刚读了一堆关于如何处理 Python 中的 StopIteration 错误的帖子,我在解决我的特定示例时遇到了麻烦。我只想用我的代码打印出 1 到 20,但它打印出错误 StopIteration。我的代码是:(我是这里的新手,所以请不要阻止我。)
def simpleGeneratorFun(n):
while n<20:
yield (n)
n=n+1
# return [1,2,3]
x = simpleGeneratorFun(1)
while x.__next__() <20:
print(x.__next__())
if x.__next__()==10:
break
Run Code Online (Sandbox Code Playgroud)
任何时候你使用x.__next__()它都会得到下一个产生的数字 - 你不会检查每个产生的数字并且跳过 10 - 所以它会在 20 后继续运行并中断。
使固定:
def simpleGeneratorFun(n):
while n<20:
yield (n)
n=n+1
# return [1,2,3]
x = simpleGeneratorFun(1)
while True:
try:
val = next(x) # x.__next__() is "private", see @Aran-Frey comment
print(val)
if val == 10:
break
except StopIteration as e:
print(e)
break
Run Code Online (Sandbox Code Playgroud)