Home > Blockchain >  Is it possible to have a function output a generator expression and a value at the same time
Is it possible to have a function output a generator expression and a value at the same time

Time:04-12

I wanted to have one function output a generator expression as well as a value (string, integer, list, tuple, etc.), I tried a making one, it looked like this:

def func():
    for x in range(3):
        yield x
    return "Hello World"

print(func())

I ran debug, it seems to run the return but doesn't output anything when I print the result

<generator object func at 0x7fb35a69ac80>

why is this happening and how can I solve this issue of it running the return statement but not returning anything.

CodePudding user response:

The return value in a generator is expressed as part of the data in the StopIteration exception. This exception occurs when you call next on a generator that has exhausted all of its remaining values.

Here is a brief example of how it can be used.

def func():
    for x in range(3):
        yield x
    return "Hello World"

gen = func()

try:
    while True:
        print(next(gen))
except StopIteration as e:
    print(e.value)
0
1
2
Hello World
  • Related