Python Variable Scope
Type of Scope
In Python, variable scope refers to the region or context in which a variable is defined and can be accessed. There are two main types of variable scope:
- Global Scope:
- Variables defined outside of any function or block have a global scope.
- They can be accessed from any part of the code, including inside functions.
- Local Scope:
- Variables defined inside a function or a block have a local scope.
- They are only accessible within that specific function or block.
Example:
# Global variable
global_variable = "I am global"
def example_function():
# Local variable
local_variable = "I am local"
print(global_variable) # Accessing global variable within the function
print(local_variable) # Accessing local variable within the function
# Trying to access local_variable outside the function will result in an error
In the example above, global_variable
has a global scope, so it can be accessed both inside and outside the function. However, local_variable
has a local scope and can only be accessed within the example_function
. Attempting to access local_variable
outside the function would result in an error.
Function Inside Function
In Python, you can define a function inside another function. This is known as a nested function. The inner function has access to variables from the outer function, creating a closure.
Example:
def outer_function(x):
def inner_function(y):
return x + y
result = inner_function(5)
return result
# Call the outer function
output = outer_function(3)
In the example above, outer_function
contains an inner function inner_function
. The inner function takes a parameter y
and returns the sum of x
(from the outer function) and y
.
The result of calling the outer function is stored in the variable output
.
Same Name with Different Scope
In Python, the scope of a variable refers to the region of the code where the variable can be accessed. When a variable with the same name is declared in different scopes, they are considered different variables.
Example:
# Global scope
global_variable = "I am global"
def example_function():
# Local scope
local_variable = "I am local"
print(local_variable) # Output: I am local
# Accessing global variable
print(global_variable) # Output: I am global
# Calling the function
example_function()
# Attempting to access local variable outside its scope (will result in an error)
# print(local_variable) # Uncommenting this line will result in an error
In the example above, global_variable
is declared in the global scope, and local_variable
is declared within the example_function
function in a local scope. The print
statements inside the function demonstrate accessing variables from both the local and global scopes.