In Python, to use a global variable inside a function, you can declare it as global
within the function. This tells Python that you’re referring to the global variable and not creating a local one with the same name.
Steps to Use a Global Variable in a Function
- Define the variable outside any function (at the global level).
- Use the
global
keyword inside the function when you need to modify it.
Example: Using a Global Variable
# Define a global variable
count = 0
def increment():
global count # Declare that we are using the global variable 'count'
count += 1 # Modify the global variable
increment()
increment()
print(count) # Output: 2
- Without the
global
keyword, the function would create a new local variable namedcount
instead of modifying the global one.
Using a Global Variable Without Modifying It
If you only need to read the global variable and don’t modify it, you can access it directly without using the global
keyword.
name = "Alice" # Global variable
def greet():
print(f"Hello, {name}!") # Access the global variable
greet() # Output: Hello, Alice!
Common Mistakes and Warnings
- Unintentional Shadowing of Global Variables: If you define a variable with the same name inside a function, Python treats it as a local variable unless explicitly declared as
global
.x = 10 # Global variable def modify(): x = 20 # Local variable, doesn't affect the global 'x' modify() print(x) # Output: 10
- Modifying Global Variables Without
global
: Attempting to modify a global variable inside a function without declaring it asglobal
will raise anUnboundLocalError
.counter = 0 # Global variable def increment(): counter += 1 # Error: UnboundLocalError
To fix this, add
global counter
before modifying it.
Alternative: Avoid Global Variables Using Function Parameters and Returns
Using global variables can make your code harder to debug and maintain. Instead, consider passing variables as function arguments and returning the results.
def increment(counter):
return counter + 1
counter = 0
counter = increment(counter)
counter = increment(counter)
print(counter) # Output: 2