+ 1
Problem with infinite generators in code playground
Suppose we have a code of a generator with while True: loop. In sololearn code playground it yields only the first value, while in IDLE it works fine: https://code.sololearn.com/cx6A4eVw6pNw/#py def natural(): i = 1 while True: yield i i += 1 if __name__ == '__main__': for i in range(10): print(next(natural())) Codeplayground output: 1 1 1 1 1 1 1 1 1 1 What is the problem here? Or is it a bug?
1 Antwort
+ 2
Problem solved by @Kirk Schafer here https://www.sololearn.com/Discuss/110922/generator-problem-in-code-playground
def natural():
i = 1
while True:
yield i
i += 1
if __name__ == '__main__':
nat = natural() #save function as a generator
for i in range(10):
print(next(nat)) #use this generator
Otherwise each time we call next(natural()) in a loop it reinitializes natural function and keeps yielding only the first element.