Python Programming - Generators - Discussion

Discussion Forum : Generators - General Questions (Q.No. 81)
81.
What happens if a generator function contains a return statement followed by a yield statement?
It raises a GeneratorExit exception
It raises a StopIteration exception
It returns the specified value and stops the generator
It is a syntax error; return and yield cannot be used together
Answer: Option
Explanation:
If a generator function contains both return and yield statements, it returns the specified value and stops the generator.
def my_generator():
    return 42
    yield  # This statement is never reached

# Example usage
gen = my_generator()
result = next(gen, None)
print(result)  # Output: 42
Discussion:
Be the first person to comment on this question !

Post your comments here:

Your comments will be displayed after verification.