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.

1def my_function():
2  local_var = "Hello, World!"
3  print(local_var)
4
5my_function()
6# Outputs: Hello, World!
7
8print(local_var)
9# Error: NameError: name 'local_var' is not defined

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:

  1. Local: Variables defined inside a function or class method. Python checks these first.
  2. Enclosing: Variables in the local scope of any and all enclosing functions from inner to outer.
  3. Global: Variables declared in the main body of the python code.
  4. 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:

 1global_var = "Hello"
 2
 3def my_function():
 4  local_var = "World!"
 5  print(global_var, local_var)
 6
 7my_function()
 8# Outputs: Hello, World!
 9
10print(global_var)
11# Outputs: Hello
12
13print(local_var)
14# Error: NameError: name 'local_var' is not defined

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.