forked from fluentpython/example-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathyetanother.py
More file actions
47 lines (39 loc) · 897 Bytes
/
yetanother.py
File metadata and controls
47 lines (39 loc) · 897 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
44
45
46
47
import sys
import collections
Result = collections.namedtuple('Result', 'total average')
def adder():
total = 0
count = 0
while True:
term = yield
try:
term = float(term)
except (ValueError, TypeError):
break
else:
total += term
count += 1
return Result(total, total/count)
def process_args(coro, args):
for arg in args:
coro.send(arg)
try:
next(coro)
except StopIteration as exc:
return exc.value
def prompt(coro):
while True:
term = input('+> ')
try:
coro.send(term)
except StopIteration as exc:
return exc.value
def main():
coro = adder()
next(coro) # prime it
if len(sys.argv) > 1:
res = process_args(coro, sys.argv[1:])
else:
res = prompt(coro)
print(res)
main()