In this lesson, you will learn how to explicitly grant a function permission to modify a variable defined at the top-level module scope using the global keyword.
The Scope Limitation
Previously, you learned that you can read a global variable inside a function without any extra steps. However, Python prevents you from modifying that variable (e.g., reassigning it) by default. If you try to assign a value to a global variable inside a function, Python treats it as a new local variable instead, leaving the original global one untouched.
Using the global Keyword
To tell Python, "I want to change the variable that exists outside this function," you must use the global keyword followed by the variable name. This acts as a declaration to the interpreter that any assignments to this name should affect the variable in the global scope rather than creating a local one.
Consider this example where we track a "score" in a game:
score = 0
def increase_score(points):
global score
score += points
increase_score(10)
print(score) # Output: 10
Without the global score line, Python would throw an UnboundLocalError because you would be trying to reference score before assigning to it, while simultaneously trying to create a local version of it. By adding global score, you explicitly authorize the function to update the top-level score variable directly.
When to Use This
While the global keyword solves the problem of modification, it should be used sparingly. Frequent reliance on global state makes functions harder to test and debug because they become dependent on variables outside their immediate control. Always consider if returning a value and reassigning it in your main code is a cleaner alternative before choosing to use global.
Key Takeaway: The global keyword allows you to modify a variable defined in the top-level module scope from within a function, preventing Python from defaulting that variable to a local scope.