In Python, the scope of a variable determines where the variable can be accessed or modified in a program. Variables can have local scope or global scope, depending on where they are defined. This article explains the difference between local and global variables with examples.
A variable defined inside a function is a local variable. It is only accessible within that function and does not affect or conflict with variables outside the function.
The following example demonstrates local variables:
# Function with a local variable def local_example(): x = 10 # Local variable print("Inside the function, x =", x) # Calling the function local_example() # Trying to access the local variable outside the function # print(x) # This will raise a NameError
Output:
Inside the function, x = 10 NameError: name 'x' is not defined
A variable defined outside any function is a global variable. It is accessible throughout the program, including inside functions (with some restrictions).
The following example demonstrates global variables:
# Global variable x = 20 def global_example(): print("Inside the function, x =", x) # Calling the function global_example() # Accessing the global variable outside the function print("Outside the function, x =", x)
Output:
Inside the function, x = 20 Outside the function, x = 20
To modify a global variable inside a function, use the global keyword. Without it, Python treats the variable as local, which can lead to errors.
The following example demonstrates modifying a global variable:
# Global variable x = 50 def modify_global(): global x # Declare x as global x = 100 print("Inside the function, x =", x) # Calling the function modify_global() # Checking the modified global variable print("Outside the function, x =", x)
Output:
Inside the function, x = 100 Outside the function, x = 100
If a local variable has the same name as a global variable, the local variable takes precedence within the function's scope.
The following example demonstrates variable shadowing:
# Global variable x = 30 def shadow_example(): x = 10 # Local variable print("Inside the function, x =", x) # Calling the function shadow_example() # Accessing the global variable print("Outside the function, x =", x)
Output:
Inside the function, x = 10 Outside the function, x = 30
Understanding the scope of variables is essential for writing efficient and error-free Python programs. Local variables are confined to their function, while global variables are accessible throughout the program. The global keyword allows modifying global variables inside functions. Experiment with these examples to deepen your understanding of variable scope in Python.