How to Use Global Variable in Python: Syntax and Examples
In Python, to use a
global variable inside a function, declare it with the global keyword before modifying it. This tells Python to use the variable defined outside the function instead of creating a new local one.Syntax
Use the global keyword inside a function to tell Python you want to use the variable defined outside the function. This allows you to modify the global variable instead of creating a new local one.
global variable_name: Declares the variable as global inside the function.- Modify or assign the variable after declaring it global.
python
x = 5 def change_global(): global x x = 10 change_global() print(x)
Output
10
Example
This example shows how to change a global variable inside a function using the global keyword. Without global, the function would create a new local variable instead of changing the global one.
python
counter = 0 def increment(): global counter counter += 1 print("Before:", counter) increment() print("After:", counter)
Output
Before: 0
After: 1
Common Pitfalls
One common mistake is to modify a global variable inside a function without declaring it global. This creates a new local variable instead of changing the global one, which can cause bugs.
Another pitfall is to use global unnecessarily when you only need to read the global variable, not modify it.
python
x = 5 def wrong_change(): x = 10 # This creates a local variable, does not change global x wrong_change() print(x) # Output will be 5, not 10 def correct_change(): global x x = 10 # This changes the global variable correct_change() print(x) # Output will be 10
Output
5
10
Quick Reference
- Use
globalonly when you need to modify a global variable inside a function. - Reading a global variable inside a function does not require
global. - Be careful to avoid accidental local variables shadowing globals.
Key Takeaways
Declare a variable as global inside a function using the
global keyword to modify it.Without
global, assigning to a variable inside a function creates a new local variable.You do not need
global to read a global variable inside a function.Using
global unnecessarily can make code harder to understand.Always test changes to global variables carefully to avoid bugs.