C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Result: The variable is changed to equal 100 in method(). And this is reflected in the global variable at the end of the program.
Python program that uses global
def method():
# Change "value" to mean the global variable.
# ... The assignment will be local without "global."
global value
value = 100
value = 0
method()
# The value has been changed to 100.
print(value)
Output
100
Here: Method2() uses nonlocal to reference the "value" variable from method(). It will never reference a local or a global.
Python program that uses nonlocal
def method():
def method2():
# In nested method, reference nonlocal variable.
nonlocal value
value = 100
# Set local.
value = 10
method2()
# Local variable reflects nonlocal change.
print(value)
# Call method.
method()
Output
100
Without nonlocal: There was no way to avoid naming conflicts between locals and enclosing methods. Global was not sufficient.
Quote: But in Python, though functions are usually defined at the top level, a function definition can be executed anywhere. This... yielded inconsistencies that were surprising to some programmers.
PEP 3104 Access to Names in Outer Scopes: python.org