Fall 2020 Berkeley cs61a hw04答案
def make_bank ( balance) :
"""Returns a bank function with a starting balance. Supports
withdrawals and deposits.
>>> bank = make_bank(100)
>>> bank('withdraw', 40) # 100 - 40
60
>>> bank('hello', 500) # Invalid message passed in
'Invalid message'
>>> bank('deposit', 20) # 60 + 20
80
>>> bank('withdraw', 90) # 80 - 90; not enough money
'Insufficient funds'
>>> bank('deposit', 100) # 80 + 100
180
>>> bank('goodbye', 0) # Invalid message passed in
'Invalid message'
>>> bank('withdraw', 60) # 180 - 60
120
"""
def bank ( message, amount) :
"*** YOUR CODE HERE ***"
nonlocal balance
if message == 'withdraw' :
if amount > balance:
return 'Insufficient funds'
balance = balance - amount
elif message == 'deposit' :
balance = balance + amount
else :
return 'Invalid message'
return balance
return bank
def make_withdraw ( balance, password) :
"""Return a password-protected withdraw function.
>>> w = make_withdraw(100, 'hax0r')
>>> w(25, 'hax0r')
75
>>> error = w(90, 'hax0r')
>>> error
'Insufficient funds'
>>> error = w(25, 'hwat')
>>> error
'Incorrect password'