Python Coding Day 21 | Mastering Python Scope: Local vs. Global Variables Explained
Mastering Python Scope: Local vs. Global Variables Explained
Watch the lesson tutorial 🔻
When writing Python code, understanding where your variables "live" is crucial. This concept is called Scope.
Think of scope as a security clearance level. Some variables have high clearance and can be seen everywhere (Global), while others are restricted to specific rooms (Local).
1. Global Scope
A variable has Global Scope when it is defined in the main body of your script, outside of any function.
Access: It can be accessed from anywhere in the file.
Lifespan: It remains in memory as long as the program is running.
2. Local Scope
A variable has Local Scope when it is defined inside a function.
Access: It can only be used within that specific function.
Lifespan: It is created when the function is called and destroyed when the function ends.
Practical Example 1: The "Shadowing" Effect
What happens if you have a Global variable and a Local variable with the same name? Python treats them as two completely different variables. The local version "shadows" (hides) the global version temporarily inside the function.
# Global variable
people = 1
def increase_people():
# Local variable
# This creates a NEW variable named 'people' only for this function.
# It does NOT change the global 'people'.
people = 2
print(f"People inside function: {people}")
# Output: People inside function: 2
increase_people()
print(f"People outside function: {people}")
# Output: People outside function: 1 (The global remains unchanged)
Practical Example 2: Reading Global Variables
Functions can look "outward" to find variables. If a variable isn't found inside the function (Locally), Python looks outside to the Enclosing scope, and finally to the Global scope.
player_health = 10 # Global variable
def game():
# Enclosing function
def drink_potion():
# Local scope
potion_strength = 2
# Python looks for player_health locally -> Not found.
# Looks in game() -> Not found.
# Looks in Global -> Found!
print(f"Player health inside: {player_health}")
drink_potion()
game()
print(f"Player health outside: {player_health}")
# Output: Player health inside: 10
# Output: Player health outside: 10
Practical Example 3: Modifying Globals with the global Keyword
By default, you cannot change a global variable inside a function; Python will just create a new local variable instead (as seen in Example 1).
To actually modify a global variable from inside a function, you must use the global keyword. This explicitly tells Python: "Do not create a new local variable; use the one that already exists outside."
score = 0 # Global variable
def defeat_enemy():
# We use the 'global' keyword to grab the outside variable
global score
# Now we can modify it directly
score = score + 1
print(f"Score inside function: {score}")
defeat_enemy()
defeat_enemy()
print(f"Final Score outside function: {score}")
# Output: Score inside function: 1
# Output: Score inside function: 2
# Output: Final Score outside function: 2
Summary
Local variables are safe and independent; they don't mess up the rest of your code.
Global variables are useful for constants, but be careful when modifying them inside functions.
Use the
globalkeyword only when you absolutely need to update a global state from inside a function.

Comments
Post a Comment