forked from fluentpython/example-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsoma_deco.py
More file actions
47 lines (40 loc) · 1002 Bytes
/
soma_deco.py
File metadata and controls
47 lines (40 loc) · 1002 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
if 'raw_input' in dir(__builtins__):
input = raw_input # para funcionar com Python 2
def ler_parcela():
parcela = input('+: ')
try:
parcela = float(parcela)
except ValueError:
return 0
return parcela
# decorator
def coro(func):
def start(*args, **kwargs):
g = func(*args, **kwargs)
next(g)
return g
return start
@coro
def somadora():
qt_parcelas = 0
total = 0
try:
while True:
parcela = yield
qt_parcelas += 1
total += parcela
print('parcelas: %d total: %d' % (qt_parcelas, total))
finally:
print('parcelas: %d total: %d media: %d' % (qt_parcelas, total, total/qt_parcelas))
def main():
coro = somadora()
while True:
parcela = ler_parcela()
if parcela:
coro.send(parcela)
else:
print('Fechando corotina...')
coro.close()
break
if __name__=='__main__':
main()