-1

I have a simple code like this:

temp = 100
def my_fun():
    temp += 10
    return temp

After I call this function my_fun() I get an error

local variable 'temp' referenced before assignment

What's wrong with my code? I set temp before I call it. But still an error.

Thanks to all.

  • Does this answer your question? [Local variable referenced before assignment in Python?](https://stackoverflow.com/questions/18002794/local-variable-referenced-before-assignment-in-python) – Faibbus Mar 25 '20 at 14:36

1 Answers1

0

Best would be to pass it in:

def my_fun(temp):
    temp += 10
    return temp

temp = 100
temp = my_fun(temp)

But if you really want to access it from the outer scope, then use:

global temp

Edit: I see you amended your question - the reason for the error is the scope of the var. Within the function that variable only exists at the function level, and since you've not actually assigned it or passed it in, it doesn't exist when you try and increment it.

michjnich
  • 2,796
  • 3
  • 15
  • 31