In programming, the range in which a variable can be referenced and remains valid is called its “Scope.” In Python, there are specific rules when handling variables defined outside a function (Global/Module variables) from within a function.
Troubles like “I tried to use an external variable inside a function but got an error” or “I changed the value but it didn’t update” are often caused by a misunderstanding of this scope.
This article explains how to reference and update global variables from within a function, and how to use the global declaration.
1. “Referencing” Global Variables
Variables defined outside a function (at the module level) can be freely referenced (read) from within the function. No special declaration is required.
# Global variable (Module variable)
APP_NAME = "Data Analyzer Pro"
def show_welcome_message():
"""
Function to reference and display a global variable
"""
# You can read the external variable from inside the function
print(f"Welcome to {APP_NAME}!")
# Call the function
show_welcome_message()
Output:
Welcome to Data Analyzer Pro!
For read-only purposes, such as configuration values or constants, you can write code this way without any issues.
2. Independence of Local Variables (Behavior on Assignment)
You need to be careful when you assign a value to a variable inside a function. In Python, if you assign a value to a variable inside a function, that variable is automatically treated as a “Local Variable” unique to that function. Even if a variable with the same name exists outside, a new, unrelated variable is created inside the function.
# Global variable
current_user = "Guest"
def login_admin():
# Because assignment happens here, 'current_user' becomes a local variable
current_user = "Admin"
print(f"[Inside] User: {current_user}")
print(f"[Before] User: {current_user}")
login_admin()
# The variable outside the function is NOT changed
print(f"[After] User: {current_user}")
Output:
[Before] User: Guest
[Inside] User: Admin
[After] User: Guest
Even though you intended to change current_user to “Admin” inside the function, only the local variable inside the function was changed, and the global variable outside remained “Guest”.
3. “Updating” Global Variables with global Declaration
If you want to rewrite (update) an external global variable from inside a function, you must use the global keyword to declare, “I will use the global variable, not a local one.”
# Global variable to count visits
visitor_count = 0
def record_visit():
# Declare global
global visitor_count
# Now you can update the global variable directly
visitor_count += 1
print(f"Visit recorded. Current count: {visitor_count}")
# Call the function
record_visit()
record_visit()
record_visit()
print(f"Final count: {visitor_count}")
Output:
Visit recorded. Current count: 1
Visit recorded. Current count: 2
Visit recorded. Current count: 3
Final count: 3
By declaring global visitor_count, the visitor_count inside the function points to the external variable, so the update by += 1 is reflected.
Note: Overusing global
While global allows you to easily change the external state, overusing it is not recommended.
- It makes it hard to track where variables are changed (causing bugs).
- It reduces the independence of functions, making reuse and testing difficult.
Whenever possible, design your code to receive values as function arguments and return results as return values. This is the trick to writing maintainable code.
Summary
- Reference: You can reference (read) variables outside a function as they are.
- Assignment: If you assign to a variable inside a function, it becomes a local variable and does not affect the outside variable.
- Update: If you want to rewrite an outside variable, declare it with
global variable_nameinside the function.
