+ 6
Infinite Generator Output without For Loop
While doing the Generators lesson in the Python tutorial, I tested the second program (below) after seeing the first one on the lesson. def infinite_sevens(): while True: yield 7 for i in infinite_sevens(): print(i) Output: >>> 7 7 7 ... ==================================== def infinite_sevens(): while True: yield 7 print(infinite_sevens()) Output: <generator object infinite_sevens at 0x00E95130> Why doesn’t the second program return the same output as the first?
6 Antworten
+ 5
I’m thinking it’s because all the 7’s print on a single line and there is a random? hexadecimal code for when the limit has been reached on the number of 7’s on that line.
EDIT:
Thanks Nikhil Dhama for the answers, but the next fn keeps the generator yielding the same value somehow.
+ 5
Nikhil Dhama
Here is my code:
def infinite_sevens():
while True:
yield 7
print(next(infinite_sevens()))
def gen():
for i in range(11):
yield i
print ("1",next(gen()))
print ("2",next(gen()))
print ("3",next(gen()))
print ("4", next(gen()))
Output:
7
1 0
2 0
3 0
4 0
How do I get a infinite amount of lines with a 7 in each of them?
+ 4
for infinite results you have to use loop,
there' isn't any other way in my knowledge,
and to use next properly, first intialise the iterator ,
iter = gen()
them use next on iter,
next(num).
iter = infinite_sevens()
then each calling of next(iter) will yield you a 7,
but using for loop is the most convenient method.
0
use,
print ( next(infinite_sevens())
it will give you values yield by generator one by one,
on every calling of next fn, it will give you the next value of generator,
generators are iteratable , so they can be used to iterate the loop.
0
def gen():
for i in range(11):
yield i
num = gen()
print ("1",next(num))
print ("2",next(num))
print ("3",next(num))
print ("4", next(num))
execute this and you will understand it. 👆
[Edit]: my bad i fixed it try it now
0
Roger Wang
next makes the generator yield same value
cuz u are yielding 7 everytime,
that's why i gave you a script to understand what's happening