36: Understanding Variables and Scope in Python

Understanding Variables and Scope in Python

Welcome to another Python programming tutorial! Today, we’ll be diving into the concept of variable scope in Python, which determines the accessibility of variables in different parts of your code. Understanding scope is crucial for writing efficient and error-free code.

 

Local and Global Variables

In Python, variables can be defined either inside a function (local) or outside a function (global). Let’s explore these concepts with examples.

Local Variables

Local variables are those defined inside a function and are only accessible within that function.

				
					def perform_operation(num1, num2, operation='sum'):
    result = num1 + num2 if operation == 'sum' else num1 * num2
    print(f"Result: {result}")
    print(f"Local variables: {locals()}")

perform_operation(1, 2, 'multiply')

				
			

Here, num1, num2, operation, and result are local variables. The locals() function returns a dictionary of all local variables.

Global Variables

Global variables are defined outside any function and can be accessed anywhere in the code.

				
					global_var = "I am global"

def display_global():
    print(global_var)

display_global()

				
			

In this example, global_var is accessible inside the display_global function.

Interaction Between Local and Global Variables

Local and global variables can coexist, but local variables take precedence over global ones within their scope.

				
					varA = 10

def test_scope(varA):
    print(f"Local varA: {varA}")

def test_global_scope():
    print(f"Global varA: {varA}")

test_scope(5)       # Outputs: Local varA: 5
test_global_scope() # Outputs: Global varA: 10

				
			

Using globals()

The globals() function returns a dictionary of all global variables.

 
				
					global_var1 = "Global 1"
global_var2 = "Global 2"

print(f"Global variables: {globals()}")

				
			

Function Definitions Within Functions

Python allows defining functions inside other functions. The inner function can access the local variables of the outer function.

				
					def outer_function():
    var_outer = "Outer Variable"

    def inner_function():
        var_inner = "Inner Variable"
        print(f"Inner Function - Local Scope: {locals()}")
    
    inner_function()
    print(f"Outer Function - Local Scope: {locals()}")

outer_function()

				
			

The inner function inner_function is only accessible within outer_function.

Example: Combining Concepts

Let’s combine all these concepts into a comprehensive example.

				
					# Global variables
global_message = "Global Message"
varA = 2

def function_one(varA, varB):
    local_message = "Local Message"
    print(f"Function One - Local Scope: {locals()}")
    print(f"Function One - Global Scope: {globals()}")
    print(f"Function One - global_message: {global_message}")
    
    def inner_function(inner_varA, inner_varB):
        print(f"Inner Function - Local Scope: {locals()}")
    
    inner_function(10, 20)

def function_two(varC, varB):
    print(f"Function Two - Local Scope: {locals()}")

function_one(1, 2)
function_two(3, 4)

				
			

Output Analysis

  • function_one and function_two have their own local scopes.
  • inner_function is defined within function_one and has access to its local variables.
  • globals() shows all global variables, including built-in ones and those defined in Jupyter Notebooks.

Summary

Understanding variable scope in Python is essential for writing clean and efficient code. By knowing how local and global variables interact and how to use locals() and globals(), you can better manage your data within your programs.