# Mutable Function Using Nonlocal def make_withdraw(balance): """Return a withdraw function with a starting balance.""" def withdraw(amount): nonlocal balance if amount > balance: return 'Insufficient funds' balance = balance - amount return balance return withdraw withdraw = make_withdraw(100) withdraw(25) # 75 withdraw(25) # 50 withdraw(60) # 'Insufficient Funds' withdraw(15) # 35 # Mutable Function Using A List def make_withdraw_list(balance): b = [balance] def withdraw(amount): if amount > b[0]: return 'Insufficient funds' b[0] = b[0] - amount return b[0] return withdraw withdraw_list = make_withdraw_list(100) withdraw_list(25) # 75 # Multiple Mutable Functions jen = make_withdraw(10000000) mitas = make_withdraw(100) mitas(10) # Mitas gets lunch # 90 jen(1000) # Jen treats the 61A staff to dinner # 9999000 mitas(2000) # Mitas wants to build a PC # 'Insufficient funds' jen(2000) # Jen lends Mitas money # 9997000 # Referential Transparency mul(add(2, mul(4, 6)), add(3, 5)) mul(add(2, 24 ), add(3, 5)) mul( 26 , add(3, 5)) mul( 26 , 8 ) # equivalent to the above account = make_withdraw(100) add(account(25), account(25)) add( 75 , account(25)) # not equivalent to the above