--Coroutines are functions that can be stopped and restarted --Stop at yield --Send the value to the return value of yield and restart
average.py
#!/usr/bin/python
def average():
total = 0.0
count = 0.0
average = 0.0
while True:
#Coroutine points
# -Generate average with yield and stop function
# -When a value is received from send, it is assigned to value and the function restarts.
value = yield average
total += value
count += 1.0
average = total/count
avg = average()
avg.next()
print avg.send(10.0)
print avg.send(20.0)
print avg.send(30.0)
--Result
10.0
15.0
20.0
Recommended Posts