To modify a global variable from inside a function in Python, you need to use the global keyword.
Here is a quick breakdown of how it works:
1. The Problem
Usually, if you just assign a value to a variable inside a function, Python treats it as a local variable. It won't change the variable with the same name outside the function.
2. The Solution: Using global
By using the global keyword inside your function, you tell Python: "Hey, don't create a new local variable; use the one that already exists in the global scope."
Example
You can see this in your current scope.py file:
eggs = 'global' # This is a global variable
def spam():
global eggs # 1. Declare that we want to use the global 'eggs'
eggs = 'spam' # 2. Now this changes the variable outside the function
print(f"Before: {eggs}")
spam()
print(f"After: {eggs}")
Key Steps:
- Define the variable outside the function.
- Inside the function, write
global variable_namebefore you try to change it. - Assign the new value.
If you don't use the global statement, Python will create a local variable named eggs inside the function, and the global eggs will remain unchanged.
Give it a try in your terminal by running python3 scope.py to see the change in action