Below program asks for nonlocal
keyword with UnboundLocalError: local variable 'balance' referenced before assignment
>>> def make_withdraw(balance):
"""Return a withdraw function with a starting balance."""
def withdraw(amount):
if amount > balance:
return 'Insufficient funds'
balance = balance - amount
return balance
return withdraw
>>> withdraw = make_withdraw(101)
>>> withdraw(25)
But, below program does not give such error when inner function shift
refers to lst
before assignment as temp = lst[0]
.
def shift_left(lst, n):
"""Shifts the lst over by n indices
>>> lst = [1, 2, 3, 4, 5]
>>> shift_left(lst, 2)
>>> lst
[3, 4, 5, 1, 2]
"""
assert (n > 0), "n should be non-negative integer"
def shift(ntimes):
if ntimes == 0:
return
else:
temp = lst[0]
for index in range(len(lst) - 1):
lst[index] = lst[index + 1]
lst[index + 1] = temp
return shift(ntimes-1)
return shift(n)
How do I understand/compare these two scenarios?