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()
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)
(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