Middle+
How can a generator receive external values through send()? Write an example of a generator that accepts the word 'stop' and stops.
sobes.tech AI
Answer from AI
A generator in Python can receive values from outside using the send() method. When calling send(value), the generator resumes execution and the yield expression returns the passed value value. This allows dynamic influence on the generator's behavior.
Example of a generator that accepts the word 'stop' and stops:
def stop_generator():
while True:
word = yield
if word == 'stop':
print('Stopping generator')
break
else:
print(f'Received word: {word}')
# Usage
g = stop_generator()
next(g) # Start generator up to the first yield
g.send('hello') # Will print: Received word: hello
g.send('world') # Will print: Received word: world
g.send('stop') # Will print: Stopping generator
Note that before the first send(), you need to start the generator up to the first yield with next().