0

Weird generator output

Using this code: def infinite_sevens(): while True: yield 7 for i in infinite_sevens(): print(i) Output: 7 7 7 7 7 7 7 7 7 (until time limit exceeded) The output is, as expected, infinite sevens (until the time limit is exceeded). However, I then modified the code a little bit, and I get a weird output that changes every time i run the program: def infinite_sevens(): while True: yield 7 print(infinite_sevens()) Output: <generator object infinite_sevens at 0x02084FB0> (I ran the program again) Output: <generator object infinite_sevens at 0x010A5130> (And again) Output: <generator object infinite_sevens at 0x027D5130> What does this output mean? Why do I get different outputs every time I run the program? Aren't the two codes basically the same? If so, why does one give an output of infinite sevens, and the other gives an output like that?

19th May 2019, 5:17 PM
Michael
3 Respostas
+ 3
Because you didn't create a generator object and getting values from it, you're just printing the name of the generator function. The hexadecimal number at the end is the address where the function is stored in memory. The same will happen if you define a function and then print it without (): def myFunction(): pass print(myFunction) # <function myFunction at 0x...>
19th May 2019, 5:20 PM
Anna
Anna - avatar
+ 2
You can get the same result with a generator function if you use next(): print(next(infinite_sevens()))
19th May 2019, 5:59 PM
Anna
Anna - avatar
0
If I write def infinite_sevens(): while True: return 7 print(infinite_sevens()) Then my output is 7. So that means that the function does have a value assigned to it because of the "return 7". Shouldn't "yield 7" be similar and show the values assigned to infinite_sevens() ?
19th May 2019, 5:30 PM
Michael