Imagine you have a toy box where the toys can only be played with in your own room (like your bedroom); however, if there are toys in the living room, you can still access them in the bedroom. In Python, variables have a similar “activity range”—scope, which determines the range where a variable can be accessed. Today, we’ll explore the two most common scopes in Python: local scope and global scope.
一、Local Scope: The “Secret” Inside Functions¶
If a variable is defined inside a function, it can only be accessed and modified within that function, just like a toy hidden in a drawer that can only be played with in the room where the drawer is located (inside the function). This is called Local Scope.
Example:
# Define a function with a local variable
def my_function():
age = 18 # age is a local variable, only valid inside my_function
print("Inside the function:", age) # Can print normally
my_function() # Output: Inside the function: 18
print("Outside the function:", age) # Error! age is a local variable and cannot be found outside
If you define a local variable with the same name as a global variable inside a function, Python will prioritize treating it as “local” rather than “global”. For example:
x = 100 # Global variable x
def my_function():
x = 200 # Here x is a local variable, overwriting the global x
print("x inside the function:", x) # Output: 200
my_function()
print("x outside the function:", x) # Output: 100 (global x remains unchanged)
二、Global Scope: The “Big Toy” in the Program¶
If a variable is defined outside all functions, it becomes a global variable (Global Scope), accessible anywhere in the entire program—like a large toy box in the living room that the whole family can access.
Directly Accessing a Global Variable:
name = "Xiaoming" # Global variable, accessible everywhere
def say_hello():
print("Hello, " + name) # Can directly use the global variable name
say_hello() # Output: Hello, Xiaoming
print(name) # Output: Xiaoming
Pitfall of Modifying a Global Variable:
Will Python throw an error if you modify a global variable inside a function? No—Python will “misinterpret” you as trying to create a local variable. For example:
score = 80 # Global variable
def update_score():
score = 90 # Python will treat this as a new local variable, not modifying the global
print("score inside the function:", score) # Output: 90
update_score()
print("score outside the function:", score) # Output: 80 (global score remains unchanged!)
Correctly Modifying a Global Variable: Use the global keyword inside the function to tell Python, “I want to modify the global variable, not create a local one.”
score = 80
def update_score():
global score # Declare: score is a global variable to be modified
score = 90
print("score inside the function:", score) # Output: 90
update_score()
print("score outside the function:", score) # Output: 90 (global score is modified)
三、Advanced: Nested Functions and nonlocal (Optional)¶
If a function is defined inside another function (nested function), the inner function can access the local variables of the outer function. However, to modify an outer function’s local variable, you need the nonlocal keyword.
Example:
def outer_function():
outer_var = "Outer variable" # outer_var is a local variable of outer, and also an "outer variable" for inner
def inner_function():
nonlocal outer_var # Declare: modify outer_var from the outer function
outer_var = "Modified outer variable"
print("inner_function's outer_var:", outer_var) # Output: Modified outer variable
inner_function()
print("outer_function's outer_var:", outer_var) # Output: Modified outer variable
outer_function()
Summary: Key Rules¶
- Local Scope: Variables defined inside a function are only valid within that function.
- Global Scope: Variables defined outside functions are accessible throughout the entire program.
- Modifying Global Variables: Use the
globalkeyword to explicitly modify a global variable inside a function. - Nested Functions: Use the
nonlocalkeyword to modify variables from an outer function’s local scope inside an inner function.
Using scopes reasonably makes code structure clearer and avoids variable name conflicts. By writing small test examples for different scenarios, you’ll quickly master this concept!