Understanding Python Variable Scope
Explore the concept of variable scope in Python, including how variables are accessible within different regions of code. Learn about local scope and how variables defined inside functions are restricted to those functions.
Python Scope
A variable is only accessible within the region it is defined. This is known as scope.
Local Scope
A variable created inside a function is part of the local scope of that function and can only be accessed within it.
Example
# A variable created inside a function is available within that function:
def myfunc():
x = 500
print(x)
myfunc()
Output
500
Function Inside Function
As demonstrated above, the variable x
is not available outside the function, but it can be accessed by any inner function:
Example
# The local variable can be accessed from a function within the function:
def myfunc():
x = 500
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
Output
500
Global Scope
A variable created in the main body of the Python code is a global variable and belongs to the global scope.
Global variables are accessible from within any scope, both global and local.
Example
# A variable created outside a function is global and can be used by anyone:
y = 500
def myfunc():
print(y)
myfunc()
print(y)
Output
500
500
Naming Variables
If you use the same variable name both inside and outside of a function, Python treats them as two separate variables—one in the global scope and one in the local scope:
Example
# The function will print the local x, and then the code will print the global x:
x = 500
def myfunc():
x = 250
print(x)
myfunc()
print(x)
Output
250
500
Global Keyword
If you need to create a global variable from within a local scope, you can use the global
keyword. This makes the variable global.
Example
# Using the global keyword to create a global variable:
def myfunc():
global z
z = 500
myfunc()
print(z)
Output
500
You can also use the global
keyword to modify a global variable inside a function.
Example
# Changing the value of a global variable inside a function:
a = 500
def myfunc():
global a
a = 250
myfunc()
print(a)
Output
250
Nonlocal Keyword
The nonlocal
keyword is used to work with variables inside nested functions. It makes the variable belong to the outer function.
Example
# Using the nonlocal keyword to modify a variable in the outer function:
def myfunc1():
x = "John"
def myfunc2():
nonlocal x
x = "Hi"
myfunc2()
return x
print(myfunc1())
Output
Hi