0

I have seen the solutions to similar errors like this one, but I still can't understand the error I'm having. This is the code:

current_savings = 0
total_cost = 1000000
r = 0.04
semmi_annual_raise_rate = 0.07
portion_down_payment = 0.25
monthly_salary = 10000


def Saving_Rate(portion_saved):
    for i in range(1,37):
        current_savings = current_savings * (1+(r/12)) + monthly_salary * portion_saved
        if i % 6 == 0:
            monthly_salary = monthly_salary * (1+semi_annual_raise_rate)
            month_savings = monthly_salary * portion_saved
    return(current_savings)

portion_saved = 0.2
Saving_Rate(portion_saved)

The error:

UnboundLocalError: local variable 'current_savings' referenced before assignment

The error seems to happen when I call the function Saving_Rate() and when I call the variable current_savings inside the function it doesn't call it from the global environment. Why?. If I already assigned it a value equal to 0 before calling the function.

Chris
  • 2,019
  • 5
  • 22
  • 67
  • You don't need `current_savings` or most other variables to be global variables. Just move them inside the `Saving_Rate` function – sshashank124 Jan 13 '20 at 03:13
  • You can tell python explicitly that `current_savings` and `monthly_salary` are global variables by adding `global current_savings,monthly_salary` line just before `while` loop. Also `semi_annual_raise_rate` is supposed to be `semmi_annual_raise_rate` inside `while` loop. – Ajay Dabas Jan 13 '20 at 03:16
  • @sshashank124 I need them to be global variables as I will use them also outside from the function environment. The function is just to do more readable/efficient the code, but I need those variables to be global. – Chris Jan 13 '20 at 04:44
  • @AjayDabas so you are saying when I define a variable in the global environment, I'm not defining it as a global variable? – Chris Jan 13 '20 at 04:45
  • You are already returning `current_savings` from the function. Why not use that value instead of trying to use global variables only? Using global variables (when you should clearly be using functions with arguments and return values) is **not** good design. Please try to fix your code accordingly – sshashank124 Jan 13 '20 at 04:46

0 Answers0