-1

The objective of this script is to provide the number of years it takes to reach target amount of money given the starting amount and annual interest rate.

I get the error :UnboundLocalError: local variable 'currentamt' referenced before assignment

startamt = float(input("Starting Amount?: "))  

targetamt = float(input("Target Amount?: "))  

air = float(input("Annual Interest Rate? "))  

currentamt = 0  

year = 0  

def main():  

    currentamt = startamt * air + currentamt

    while currentamt < targetamt:  

        year = year + 1  

print('year')  

if __name__ == '__main__':  

    main()
bhansa
  • 7,282
  • 3
  • 30
  • 55
Jared Lim
  • 1
  • 1
  • The objective of this script is to provide the number of years it takes to reach target amount of money given the starting amount and annual interest rate. I get the error :UnboundLocalError: local variable 'currentamt' referenced before assignment – Jared Lim Oct 02 '17 at 17:49
  • Hello and welcome to SO. May I suggest you copy-paste the full exception trace when you encounter an error? Otherwise you're omitting useful information that may help us help you. – spectras Oct 02 '17 at 17:54
  • 2
    Possible duplicate of [Local (?) variable referenced before assignment](https://stackoverflow.com/questions/11904981/local-variable-referenced-before-assignment) – bhansa Oct 02 '17 at 17:55
  • all variables inside `main()` are local to itself. it cannot access global variables unless you declare it so. (which, many would argue is a bad practice) – Mangohero1 Oct 02 '17 at 17:57

1 Answers1

0

Your main function doesn't know what currentamt is unless you pass it in as an argument. Your loop doesn't modify currentamt so it will loop infinitely. In the end you print 'year' which is a string. If your loop were to work it would eventually print 'year' in the console. Instead you want to print year which is the variable containing year. See the solution below for reference.

def main(currentamt):  
    year = 0 
    startamt = float(input("Starting Amount?: "))  
    targetamt = float(input("Target Amount?: "))  
    air = float(input("Annual Interest Rate? "))  

    while currentamt < targetamt:  
        currentamt = startamt * air + currentamt
        year = year + 1
    print(year)  

if __name__ == '__main__':  
    currentamt = 0
    main(currentamt)
BHawk
  • 2,382
  • 1
  • 16
  • 24