In Python, the scope of a variable determines where in your program that variable can be accessed and modified. It's a set of rules that defines the "visibility" of a variable. Understanding scope is crucial for writing clean, bug-free code and avoiding naming conflicts. Python has two primary scopes: local and global.
1. Local Scope
A variable created inside a function has a local scope. This means it only exists and can only be accessed from within that specific function. Once the function finishes executing, the local variable is destroyed.
- Use Case: For temporary variables that are only needed to perform a function's specific task. This is the most common type of variable. It prevents different functions from accidentally interfering with each other's variables, even if they have the same name.
Python
# --- Local Scope Example ---
def calculate_price():
# 'base_price' and 'tax' are local variables.
# They only exist inside this function.
base_price = 100
tax = 0.18
total = base_price + (base_price * tax)
print(f"Inside the function, the total is: {total}")
# Call the function to create and use the local variables.
calculate_price()
# The following line would cause a NameError because 'base_price'
# cannot be accessed from outside the function.
# print(base_price)
2. Global Scope
A variable created outside of any function, in the main body of your script, has a global scope. This means it can be accessed (read) from anywhere in your script, including from inside any function.
- Use Case: For constants or configuration settings that need to be available to many different functions throughout your program (e.g., a tax rate, a file path, or a game's difficulty setting).
Python
# --- Global Scope Example ---
# 'tax_rate' is a global variable.
tax_rate = 0.18
def calculate_total(base_price):
# The function can ACCESS (read) the global 'tax_rate' variable.
total = base_price + (base_price * tax_rate)
return total
# Call the function, which uses the global variable.
final_price = calculate_total(100)
print(f"The final price is: {final_price}")
# The global variable can also be accessed directly.
print(f"The global tax rate is: {tax_rate}")
3. The global Keyword
By default, you can only read a global variable from inside a function. If you try to assign a new value to it, Python will create a new local variable with the same name instead of changing the global one. To explicitly modify a global variable from within a function, you must use the global keyword.
- Use Case: When the specific purpose of a function is to change the state of a global variable. This is common for things like updating a global counter, changing a game score, or modifying a shared application state.
Python
# --- The 'global' Keyword Example ---
# 'game_score' is a global variable.
game_score = 0
def increase_score(points):
# Use the 'global' keyword to indicate we want to MODIFY the global variable.
global game_score
game_score += points # This now changes the global 'game_score'
print(f"Score increased by {points}!")
print(f"Initial score: {game_score}")
increase_score(10)
increase_score(5)
print(f"Final score: {game_score}")