1
num = 0
def func():
    print(num)
func()

The above function is supposed to print the value held by variable num and it works. By this, i would assume that func has access of num. But when i try to change the value of num inside the function, it gives me an error. UnboundLocalError: local variable 'num' referenced before assignment

num = 0
def func():
    print(num)
    num += 1
func()

Why is this happening?

1 Answers1

-2

The num variable isn't in the function's local scope, so you can't modify it inside the function since the variable contains an immutable data type (int). You can take advantage of global keyword or define the variable inside the function. num = 0 def func(): global num print(num) num += 1 func()

  • The `num` variable *is in the local scope* that's the problem. And the type a variable is referring to doesn't affect if it can be modified or not. – juanpa.arrivillaga Aug 16 '20 at 22:42
  • The num variable is local to what scope exactly? To the functions scope? I guess not. It's currently on same scope with the function. Here's the problem num +=1 the right hand is evaluated first and there's no num variable at run time to modify since the original num is immutable. If num was a list, there wouldn't be problem – Anya Precious Aug 16 '20 at 22:47
  • 1
    No. Try it with a list, you will get **the exact same error** and the problem is that `num` is local to `func` that is **what the error message is telling you**. Your ideas about mutability being relevant here are very mistaken – juanpa.arrivillaga Aug 16 '20 at 23:00