When you start writing functions, you'll notice something important: not all variables are accessible from everywhere in your program. Where you define a variable determines where you can use it. This concept is known as variable scope. Understanding scope is fundamental to organizing your code and preventing unexpected behavior.
Think of it like having different rooms in a house. Some items belong in a specific room (like your toothbrush in the bathroom), while others might be accessible from many places (like the main light switch). Variables work similarly.
Variables that you define inside a function definition are called local variables. They exist only within that specific function. Once the function finishes executing, these variables disappear, and their memory is freed up. Trying to access a local variable from outside its function will result in an error.
Consider this example:
def greet_user():
message = "Hello from inside the function!" # message is local to greet_user
print(message)
greet_user()
# Now, let's try to access 'message' outside the function:
# print(message) # This line will cause a NameError
If you run this code and uncomment the last line, Python will stop and report a NameError
. This happens because the variable message
only exists within the scope of the greet_user
function. Outside of that function, Python doesn't know what message
refers to.
This localization is actually a very useful feature. It means you can use common variable names like i
, count
, or temp
inside different functions without worrying about them interfering with each other. Each function gets its own private workspace for its local variables.
Variables defined outside of any function definition are called global variables. They reside in the main body of your script, often called the global scope or module scope. These variables can typically be accessed (read) from anywhere in your script, including from within any function defined after them.
Let's see an example:
app_version = "1.0" # app_version is a global variable
def display_version():
print("Inside the function, app version is:", app_version) # Accessing the global variable
print("Outside the function, app version is:", app_version)
display_version()
Running this code produces:
Outside the function, app version is: 1.0
Inside the function, app version is: 1.0
As you can see, the display_version
function can read the value of the global variable app_version
without any issues.
When you use a variable name within a function, Python follows a specific order to find out what value it refers to:
(Note: There are other scopes like enclosing function scopes and built-in scopes, but for now, understanding the distinction between local and global is the most significant step.)
This search order explains why functions can access global variables but the outside code cannot access local variables.
What happens if you define a local variable inside a function with the same name as a global variable?
animal = "Global Fox" # Global variable
def print_local_animal():
animal = "Local Bear" # Local variable with the same name
print("Inside function:", animal)
print("Outside function (before call):", animal)
print_local_animal()
print("Outside function (after call):", animal)
Output:
Outside function (before call): Global Fox
Inside function: Local Bear
Outside function (after call): Global Fox
Inside the print_local_animal
function, the assignment animal = "Local Bear"
creates a new, local variable named animal
. This local variable takes precedence within the function's scope, effectively hiding or "shadowing" the global variable of the same name. When print_local_animal
finishes, its local animal
variable disappears. Importantly, the global animal
variable remains unchanged throughout this process.
This behavior prevents functions from accidentally modifying global variables just by using the same name locally.
global
KeywordUsually, functions should operate on their inputs (arguments) and produce outputs (return values). This makes them self-contained and easier to understand. However, there might be situations where a function needs to explicitly modify a global variable.
If you try to assign a value to a variable inside a function that has the same name as a global variable, Python assumes you want to create a new local variable (as seen in the shadowing example). To tell Python you actually want to modify the global variable, you must use the global
keyword before you assign to it within the function.
counter = 0 # Global variable
def increment_counter():
global counter # Declare intention to use the global 'counter'
counter += 1 # Modify the global variable
print("Counter inside function:", counter)
print("Counter before:", counter)
increment_counter()
increment_counter()
print("Counter after:", counter)
Output:
Counter before: 0
Counter inside function: 1
Counter inside function: 2
Counter after: 2
Here, global counter
tells the increment_counter
function that counter
refers to the variable in the global scope, not a new local one. Therefore, the counter += 1
operation modifies the original global variable.
Use global
Sparingly: While the global
keyword provides a way to modify global state, it's generally recommended to use it cautiously. Functions that modify global variables can have side effects that are not obvious from where the function is called. This can make your program harder to reason about and debug. Often, a better approach is to have the function return
the new value, and let the code outside the function update the global variable if needed.
# Alternative approach (often preferred)
counter = 0 # Global variable
def calculate_new_count(current_count):
# This function doesn't modify global state directly
return current_count + 1
print("Counter before:", counter)
counter = calculate_new_count(counter) # Update global variable based on return value
print("Counter after first update:", counter)
counter = calculate_new_count(counter)
print("Counter after second update:", counter)
Output:
Counter before: 0
Counter after first update: 1
Counter after second update: 2
This alternative achieves the same result but keeps the function (calculate_new_count
) self-contained and free from modifying global variables directly.
Understanding the difference between local and global scope is essential for writing clear, correct, and maintainable Python functions. It helps you manage where data lives in your program and prevents unintended modifications to variables.
© 2025 ApX Machine Learning