How to change variable in function scope from inner function
Question:
Same code will work in JS, but in python it will not change variable, how do you change variables in nested functions? Thanks in advance and sorry for noob question
def sample():
a = False
def sample2():
a = True
sample2()
return a
Answers:
Use nonlocal to modify variables outside the scope of the function.
def sample():
a = False
def sample2():
nonlocal a
a = True
sample2()
return a
use nonlocal
def sample():
a = False
def sample2():
nonlocal a
a = True
sample2()
return a
The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.
def sample():
a = False
def sample2():
nonlocal a
a = True
sample2()
return a
This should work.
Same code will work in JS, but in python it will not change variable, how do you change variables in nested functions? Thanks in advance and sorry for noob question
def sample():
a = False
def sample2():
a = True
sample2()
return a
Use nonlocal to modify variables outside the scope of the function.
def sample():
a = False
def sample2():
nonlocal a
a = True
sample2()
return a
use nonlocal
def sample():
a = False
def sample2():
nonlocal a
a = True
sample2()
return a
The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals.
def sample():
a = False
def sample2():
nonlocal a
a = True
sample2()
return a
This should work.