forked from fluentpython/example-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoroadder0.py
More file actions
43 lines (36 loc) · 894 Bytes
/
coroadder0.py
File metadata and controls
43 lines (36 loc) · 894 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
"""
Closing a generator raises ``GeneratorExit`` at the pending ``yield``
>>> adder = adder_coro()
>>> next(adder)
0
>>> adder.send(10)
10
>>> adder.send(20)
30
>>> adder.send(30)
60
>>> adder.close()
-> total: 60 terms: 3 average: 20.0
Other exceptions propagate to the caller:
>>> adder = adder_coro()
>>> next(adder)
0
>>> adder.send(10)
10
>>> adder.send('spam')
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
"""
def adder_coro(initial=0):
total = initial
count = 0
try:
while True:
term = yield total
total += term
count += 1
except GeneratorExit:
average = total / count
msg = '-> total: {} terms: {} average: {}'
print(msg.format(total, count, average))