Variables & functions
In Python, the scope of a variable refers to the region of code where the variable is accessible and can be used. There are two main types of variable scope: local and global.
- Local Scope:
Variables that are defined within a function are said to have a local scope. These variables can only be accessed and manipulated within the function where they are defined. Once the function completes execution, the local variables are destroyed, and their values are no longer accessible.
Example of local scope:
def my_function():
x = 10 # This is a local variable
print(x)
my_function()
print(x) # This will result in an error
In this example, "x" is defined inside the "my_function()"" and can only be accessed within that function.
Variables that are defined outside of any function or block have a global scope. These variables can be accessed from anywhere within the code, both inside and outside functions. Global variables remain in memory for the entire duration of the program's execution.
Example of global scope:
y = 20 # This is a global variable
def another_function():
print(y)
another_function()
print(y)
Here, "y" is a global variable that can be accessed both inside and outside the function.
A variable's scope determines where you can access and modify its value:
- Inside a function, you can access both local and global variables, but modifications to global variables require using the "global" keyword.
- Outside a function, you can access global variables, but local variables from a function are not directly accessible.
If you define a local variable with the same name as a global variable within a function, the local variable "shadows" the global variable within that function's scope. This means that any references to that variable within the function will refer to the local variable, not the global one.
z = 30 # Global variable
def yet_another_function():
z = 40 # This is a local variable, shadowing the global z
print(z)
yet_another_function()
print(z) # This will still refer to the global z
Understanding variable scope is crucial for writing clean, organized, and bug-free code. Careful consideration of scope helps prevent unintended variable modifications and ensures that variables are used in the appropriate context.