How to Use Global Keyword in Python: Syntax and Examples
In Python, use the
global keyword inside a function to modify a variable defined outside that function. This tells Python to use the global variable instead of creating a new local one.Syntax
The global keyword is used inside a function to declare that a variable refers to the global scope variable. This allows you to modify the global variable from within the function.
global variable_name: Declares the variable as global.- After this declaration, assignments affect the global variable, not a local copy.
python
def function(): global variable_name variable_name = new_value
Example
This example shows how to use global to change a variable defined outside the function.
python
count = 0 def increment(): global count count += 1 print(f'Before increment: {count}') increment() print(f'After increment: {count}')
Output
Before increment: 0
After increment: 1
Common Pitfalls
Without global, assigning a value to a variable inside a function creates a new local variable, leaving the global variable unchanged. This often causes bugs when you expect the global variable to update.
Also, using global unnecessarily can make code harder to understand and debug.
python
x = 5 def wrong(): x = 10 # This creates a local variable, does not change global x wrong() print(x) # Output: 5 def right(): global x x = 10 # This changes the global variable right() print(x) # Output: 10
Output
5
10
Quick Reference
- Use
globalinside functions to modify global variables. - Declare
globalbefore assigning to the variable. - Without
global, assignments create local variables. - Use
globalsparingly to keep code clear.
Key Takeaways
Use
global inside a function to modify a variable defined outside it.Without
global, assignments inside functions create local variables.Declare
global before assigning to the variable to affect the global scope.Avoid overusing
global to keep your code easy to understand.Remember
global only works inside functions, not in global scope.