0
Next() function.
def numbers(x): for i in range(x): if i%2==0: yield i value=numbers(11) print(next(value)) print(next(value)) print(next(value)) print(next(value)) print(next(value)) >this program gives output as 0,2,4,6,8,10 but , def numbers(x): for i in range(x): if i%2==0: yield i print(next(numbers(11)) print(next(numbers(11)) print(next(numbers(11)) print(next(numbers(11)) print(next(numbers(11)) print(next(numbers(11)) >this program always give output 0 ..why??
2 Respostas
+ 1
In 2nd program , you are calling the next function only once on each function unlike the first one that has multiple next call on same function .
0
your function define/return a generator (because use of 'yield' keyword inside)...
then you must store it in a variable and call next(generator) to get each values returned by 'yield' statement(s) ^^
in the second case, you build a new generator at each next call, so you only get the first value returned by 'yield' at each call ;P