-
Notifications
You must be signed in to change notification settings - Fork 1
/
lesson-20.py
executable file
·109 lines (94 loc) · 2.99 KB
/
lesson-20.py
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#!/usr/bin/env python3
# lesson-20.py - eliminate global variable by passing around balance
#
# Learn:
# avoid globals by passing variables
# keep global space unpolluted
import sys
def showBalance(balance):
print('Your balance is $%d.' % balance)
print()
def showTransactions(transactions, balance):
print(' op amount balance')
print('-------- ------- -------')
print(' %7d (starting)' % balance)
for transaction in transactions:
[op, amount] = transaction
if op == 'w':
opLabel = 'withdraw'
balance -= amount
else:
opLabel = "deposit"
balance += amount
print('%-8s %7d %7d' % (opLabel, amount, balance))
print()
def withdrawal(amount, balance, transactions):
if amount > balance:
print("Sorry, you don't have that much!")
else:
print('Withdraw $%d.' % amount)
balance -= amount
transactions.append(['w', amount])
showBalance(balance)
return (balance, transactions)
def deposit(amount, balance, transactions):
print('Deposit $%d.' % amount)
balance += amount
transactions.append(['d', amount])
showBalance(balance)
return (balance, transactions)
def getOperation():
op = input('Enter d for deposit, w for withdrawal, t for transactions, or q to quit: ')
if op != 'q' and op != 'd' and op != 'w' and op != 't':
print('Invalid operation. Please try again.')
op = None
return op
def getAmount():
amount = None
try:
amount = int(input('Enter amount: '))
if amount <= 0:
print('The amount must be positive.')
amount = None
except:
print('Invalid amount. Please try again.')
return amount
def getStartingBalance(balance):
if len(sys.argv) > 1:
try:
balance = int(sys.argv[1])
if balance < 0:
print('The balance cannot be negative.')
balance = None
except:
print('Invalid starting balance.')
print('usage: %s [amount]' % sys.argv[0])
print('where amount is a starting balance dollar amount')
balance = None
return balance
def processTransactions(balance):
startingBalance = balance
transactions = []
while True:
amount = None
op = getOperation()
if op == 'q':
break
elif op == 't':
showTransactions(transactions, startingBalance)
elif op is not None:
amount = getAmount()
if amount is None:
pass
elif op == 'd':
(balance, transactions) = deposit(amount, balance, transactions)
else:
(balance, transactions) = withdrawal(amount, balance, transactions)
def main():
balance = 100
balance = getStartingBalance(balance)
if balance is not None:
print('Welcome to the bank.')
showBalance(balance)
processTransactions(balance)
main()