+ 3
How can I reassing a global variables in local namespaces in Python?
I have a problem of not being able to reassing global variables in local namespaces. For example you can't change global x's value in example: global x x = 5 def f(): x = 10 I thought I could have fixed that by: global x x = 5 def f(): nonlocal x x = 10 But it results in syntax errors. Is there a correct way to fix that problem?
5 Respostas
+ 7
Seb TheS apologizes, I didn't know that and thank you for letting me know.
And I just read about nonlocal variable, it says:
Nonlocal variable are used in nested function whose local scope is not defined. This means, the variable can be neither in the local nor the global scope.
And a change in nonlocal variable changes the value of local variable.
+ 3
Yes syntax error 'cause there's no keyword called nonlocal in Python, lol.
In the first code, in the function's scope, it cannot find that x is a global variable but it sees x as a local variable within the function with a value of 10. And hence upon printing x outside the function, it'll have a value of 5 and not 10.
You must declare x as global inside the function.
def f():
global x
x=10
+ 2
Seb TheS The nonlocal keyword allows to assign to variables in an outer scope, but not a global scope. So you can't use
nonlocal in your function because then it would try to assign to a global scope. That's why you have got a SyntaxError. You can use nonlocal in a nested function only
To change the global variable write global x inside the function:
x = 5
def f():
global x
x = 10
print(x) #5
f()
print(x) #10
0
You need to declare global variable inside funtion:
x = 5
def f():
global x
x = 10