Python Forum

Full Version: Generators don't work
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,

I'm trying to use generators, however using "print(next(gen))" doesn't print anything, I obtain just "Process finished with exit code 0". Here's my code:
def get_values():
    yield "Hello"
    yield "World"
    yield 123

def get_values2():
    gen = get_values()
    print(next(gen))
    print(next(gen))
    print(next(gen))
you never call get_values2()
Many thanks for formatting and reply. I tried to use
example_get_values
instead, like in tutorial here: https://www.youtube.com/watch?v=tmeKsb2F...LL&index=3, however I still obtain the same output. How should I change the code? Thanks again.
what is example_get_values? It is not present in your code. With your code you should do
def get_values():
    yield "Hello"
    yield "World"
    yield 123
 
def get_values2():
    gen = get_values()
    print(next(gen))
    print(next(gen))
    print(next(gen))
get_values2()
That said this code may be written much better. For example

def generate_values():
    values = ['Hello', "world", 123]
    for item in values:
        yield item

gen = generate_values()
for item in gen:
    print(item)
Perfect, now I understand, I have to call the function. But still I don't get it why here they didn't have to call the function for it to work perfectly:

https://www.youtube.com/watch?v=tmeKsb2F...dex=3&t=1s at time 01.30
(Jan-16-2025, 03:10 PM)svalencic Wrote: [ -> ]But still I don't get it why here they didn't have to call the function for it to work perfectly:
That's because they don't show you the code where they call the function. They only show you part of the code.
(Jan-16-2025, 04:04 PM)Gribouillis Wrote: [ -> ]
(Jan-16-2025, 03:10 PM)svalencic Wrote: [ -> ]But still I don't get it why here they didn't have to call the function for it to work perfectly:
That's because they don't show you the code where they call the function. They only show you part of the code.

OK, that explains it, thanks a lot!
The code works:
[deadeye@nexus ~]$ python
Python 3.13.1 (main, Dec  4 2024, 18:05:56) [GCC 14.2.1 20240910] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def get_values():
...     yield "Hello"
...     yield "World"
...     yield 123
...
... def get_values2():
...     gen = get_values()
...     print(next(gen))
...     print(next(gen))
...     print(next(gen))
...
>>> get_values2()
Hello
World
123