local error variable

Asked

Viewed 16 times

0

g = 10
def b():
    g = g + 1
b()

When I do this error appears

UnboundLocalError: local variable 'g' referenced before assignment

I can’t put the g variable inside def b() For every time I call b() she will return the value to 10. I also tried to define it as global, but it didn’t work.

  • the variable g outside the function is a global variable, every variable declared in a python module is global, within the function is a local this variable is only accessed inside the function, to access the global instance inside the local and change it needs to use the global notation.... within the function b ... global g...... and then g=g +1 and ready assigned 1 the global variable in a local scope.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.