local Statements
Understanding local Statements
In Python, a variable is only available from inside the region it is created, known as its “scope”. A local variable is one defined within a function and is not accessible outside that function. It exists only within the scope of the function. Here’s a simple example.
In the preceding code snippet, local_var
is a local variable of the my_function
. You can access local_var
within my_function
, but once the function execution ends, local_var
is destroyed.
If you try to access local_var
after the function call, Python throws a NameError
because local_var
is not defined outside the function scope.
Python’s Scope Resolution
Here’s one thing you need to bear in mind: Python works on a LEGB rule when it comes to variable scope. This LEGB stands for:
- Local: Variables defined inside a function or class method. Python checks these first.
- Enclosing: Variables in the local scope of any and all enclosing functions from inner to outer.
- Global: Variables declared in the main body of the python code.
- Built-in: Pre-defined in Python (like open, range, syntax errors).
So, Python will first check if the variable is a Local one, if not it checks for enclosing variables, then global, and finally the built-in ones.
Note
Python functions create a new local scope when called. Variables assigned in this scope are not related to variables in the global scope.
Global vs Local Variables in Python
To better illustrate the contrast between local and global scopes, let’s modify my_function
to include a global variable:
Here, global_var
is defined outside any function, making it a global variable. Inside my_function
, we are able to access global_var
as well as our local_var. This because global_var
exists in the global scope – it’s available everywhere in our code.
Conversely, local_var cannot be accessed outside the function as it only existed during the execution of my_function
.
Understanding the differences between local and global scopes can help you manage and manipulate variable access more effectively in function-heavy Python scripts.