The Example is about keep tracking of the remaining balance after each withdrawal. The example is implemented as follows:
class exmaple
def make_withdraw_list(balance):
b = [balance]
def withdraw(amount):
if amount > b[0]:
return 'Insufficnent funds'
b[0] = b[0] - amount
return b[0]
return withdraw
withdraw = make_withdraw_list(100)
withdraw(25) # return 75
withdraw(25) # return 50
withdraw(60) # return 'Insufficient Fund'
He uses b = [balance] since a list is mutable. But if I removes the square brackets, uses a value instead
my exmaple
def make_withdraw_list2(balance):
b = balance
def withdraw(amount):
if amount > b:
return 'Insufficnent funds'
b = b - amount
return b
return withdraw
withdraw2 = make_withdraw_list2(100)
withdraw2(25)
I got an error:
UnboundLocalError Traceback (most recent call last)
/var/folders/94/kdblvky13td3dsb87sjkw6km0000gn/T/ipykernel_796/3313068670.py in <module>
----> 1 withdraw2(25)
/var/folders/94/kdblvky13td3dsb87sjkw6km0000gn/T/ipykernel_796/1105220220.py in withdraw(amount)
2 b = 100
3 def withdraw(amount):
----> 4 if amount > b:
5 return 'Insufficnent funds'
6 b = b - amount
UnboundLocalError: local variable 'b' referenced before assignment
Is b now still mutable? Is this error due to immutable? I don't understand why this happens. I cannot login into piazza (not a Berkeley student)