Q:

'UnboundLocalError: local variable 'lower' referenced before assignment'

balance = float(input('Enter a starting balance: '))

annualInterestRate = float(input('Enter an annual interest rate: '))

monthlyInterestRate = float(annualInterestRate/12)

balance2 = balance

lower = float(balance/12)

upper = float((balance*(1+monthlyInterestRate)**12)/12)

epsilon = 0.01

guess = float((lower+upper)/2)

def findMin(balance2, guess):

    print(lower, upper)
    for i in range(12):
        balance2 -= guess
        balance2 += (balance2*monthlyInterestRate)
    if round(balance2, 2): 
        return guess
    elif balance2 > 1:
        lower = guess
    elif balance2 < 1:
        upper = guess
    guess = (upper+lower)/2
    balance2 = balance
    findMin(balance2, guess)

findMin(balance2, guess)

print(guess)

When I run the code above I'm getting an UnboundLocalError (it says that 'lower' is referenced before assignment). I'm really confused because, as you can see, 'lower' is assigned a value before the function so why isn't it being picked up from outside the function?? Any help would be greatly appreciated! Thanks.

A:

You need to add global in the beginning of the function to make changes to lower and upper.
balance = float(input('Enter a starting balance: '))

annualInterestRate = float(input('Enter an annual interest rate: '))

monthlyInterestRate = float(annualInterestRate/12)

balance2 = balance

lower = float(balance/12)

upper = float((balance*(1+monthlyInterestRate)**12)/12)

epsilon = 0.01

guess = float((lower+upper)/2)

def findMin(balance2, guess):
    global lower, upper #Change
    print(lower, upper)
    for i in range(12):
        balance2 -= guess
        balance2 += (balance2*monthlyInterestRate)
    if round(balance2, 2): 
        return guess
    elif balance2 > 1:
        lower = guess
    elif balance2 < 1:
        upper = guess
    guess = (upper+lower)/2
    balance2 = balance
    findMin(balance2, guess)

findMin(balance2, guess)

print(guess)

