Python Global Variables
In Python, a global variable is a variable that is declared outside a function and can be accessed from anywhere in the program.
Global variables are useful when you want to share data across multiple functions.
What Is a Global Variable?
A variable created outside of all functions is called a global variable.
- It belongs to the global scope
- It can be accessed anywhere in the file
- It exists for the entire lifetime of the program
python
x = 10
def show():
print(x)
show()
Accessing Global Variables Inside a Function
You can read a global variable inside a function without any special keyword.
python
count = 5
def display():
print(count)
display()
python
name = "Python"
def greet():
print("Hello", name)
greet()
python
price = 100
def show_price():
print(price)
show_price()
Local vs Global Variable
If a variable is created inside a function, it is a local variable and cannot be accessed outside.
python
def my_func():
x = 20
print(x)
my_func()
python
# print(x) # Error: x is not defined
Using the global Keyword
To modify a global variable inside a function, you must use the
global keyword.python
x = 10
def change():
global x
x = 20
change()
print(x)
python
counter = 0
def increment():
global counter
counter += 1
increment()
print(counter)
python
status = "OFF"
def turn_on():
global status
status = "ON"
turn_on()
print(status)
Global Variables with Same Name as Local
If a variable with the same name exists inside a function, Python treats it as local by default.
python
x = 10
def my_func():
x = 5
print(x)
my_func()
print(x)
When to Use Global Variables
Global variables are useful when:
- Multiple functions need shared data
- Configuration values are required globally
- Constants are defined once and reused
python
APP_NAME = "MyApp"
def show_app():
print(APP_NAME)
show_app()
Best Practices for Global Variables
- Use global variables sparingly
- Prefer constants (uppercase names)
- Avoid modifying globals frequently
- Use function parameters when possible
python
PI = 3.14
def area(radius):
return PI * radius * radius
print(area(5))
Common Mistake
Trying to modify a global variable without
global keyword.python
x = 10
def update():
x = x + 1 # Error
update()
Summary
- Global variables are declared outside functions
- They can be accessed anywhere
- Use
globalkeyword to modify them inside functions - Overusing globals can make code hard to manage
Exercise
- Create a global variable and access it inside a function
- Modify a global variable using
globalkeyword - Try creating a local variable with the same name