When trying to use the local and non-local variables x
in inner()
as shown below:
x = 0
def outer():
x = 5
def inner():
x = 10 # Local variable
x += 1
print(x)
nonlocal x # Non-local variable
x += 1
print(x)
inner()
outer()
Or, when trying to use the global and non-local variables x
in inner()
as shown below:
x = 0
def outer():
x = 5
def inner():
global x # Global variable
x += 1
print(x)
nonlocal x # Non-local variable
x += 1
print(x)
inner()
outer()
I got the error below:
SyntaxError: name 'x' is used prior to nonlocal declaration
And, when trying to use the local and global variables x
in inner()
as shown below:
x = 0
def outer():
x = 5
def inner():
x = 10 # Local variable
x += 1
print(x)
global x # Global variable
x += 1
print(x)
inner()
outer()
Or, when trying to use the non-local and global variables x
in inner()
as shown below:
x = 0
def outer():
x = 5
def inner():
nonlocal x # Non-local variable
x += 1
print(x)
global x # Global variable
x += 1
print(x)
inner()
outer()
I got the error below:
SyntaxError: name 'x' is used prior to global declaration
In addition, when trying to define the non-local and global variables x
in inner()
as shown below:
x = 0
def outer():
x = 5
def inner():
nonlocal x # Non-local variable
global x # Global variable
inner()
outer()
Or, when trying to define the global and non-local variables x
in inner()
as shown below:
x = 0
def outer():
x = 5
def inner():
global x # Global variable
nonlocal x # Non-local variable
inner()
outer()
I got the error below:
SyntaxError: name 'x' is nonlocal and global
And, when trying to define the local and non-local variables x
in inner()
as shown below:
x = 0
def outer():
x = 5
def inner():
x = 10 # Local variable
nonlocal x # Non-local variable
inner()
outer()
I got the error below:
SyntaxError: name 'x' is assigned to before nonlocal declaration
And, when trying to define the local and global variables x
in inner()
as shown below:
x = 0
def outer():
x = 5
def inner():
x = 10 # Local variable
global x # Global variable
inner()
outer()
I got the error below:
SyntaxError: name 'x' is assigned to before global declaration
So, how can I use local, non-local and global variables in the same inner function without the errors above?