The scope of a variable refers to the part of the program where that variable is accessible. In Python, there are two main types of variable scope: local and global.
Local variables: These are defined within a function. Their scope is limited to that function and they are not accessible outside of it.
Global variables: These are defined outside of any function or in a global scope. They can be accessible from anywhere in the program, both inside and outside of functions.
If you want to learn more
consult the Introduction to Programming Course read more
Local Variables
Variables defined within a function have a local scope. This means that they are only accessible within that function. If we try to access a local variable from outside the function, Python will generate an error.
Example of Local Variable
def my_function():
local_variable = "Hello World"
print(local_variable)
my_function()
# print(local_variable) # This would generate an error
In this example, local_variable
is defined within the my_function
and is only accessible within that function.
Global Variables
Variables defined outside of any function or in a global scope have a global scope. This means they are accessible from anywhere in the program, including inside functions.
Example of Global Variable
global_variable = "I am global"
def print_global():
print(global_variable)
print_global() # Result: I am global
print(global_variable) # Also accessible outside the function
In this case, global_variable
is defined outside of the print_global
function, so it is a global variable and can be accessible from anywhere in the program.
Using the global
Keyword
In some cases, we may need to modify a global variable from within a function. To do so, we need to use the global
keyword.
Example of Using global
global_variable = "I am global"
def modify_global():
global global_variable
global_variable = "Modified within the function"
print(global_variable)
modify_global() # Result: Modified within the function
print(global_variable) # Now the global variable has been modified
By using global global_variable
within the modify_global
function, we are telling Python that we want to modify the global variable global_variable
.
Scope of Variables in Nested Functions
If we define a function within another function, the inner function can access the local variables of the outer function, but cannot modify them directly. However, if we use the nonlocal
keyword, we can modify variables of the outer function.
Example of Nested Functions
def outer_function():
outer_variable = "I am from the outer function"
def inner_function():
nonlocal outer_variable
outer_variable = "Modified by the inner function"
print("From inner function:", outer_variable)
inner_function()
print("From outer function:", outer_variable)
outer_function()
In this example, inner_function
can access and modify the outer_variable
of outer_function
due to the use of nonlocal
.