The global
global
Defining global variables
A global variable is defined outside of any function, making it accessible throughout the entire script. Functions can read global variables without any special declaration.
# Global variable
x = 10
def print_x():
print(x)
print_x() # Output: 10
In this example, x
is a global variable, and the print_x()
Modifying global variables with global
To modify a global variable inside a function, you must use the global
# Global variable
counter = 0
def increment():
global counter # Declare that we want to use the global variable
counter += 1 # Increment the global variable
increment()
print(counter) # Output: 1
increment()
print(counter) # Output: 2
Key Points in the Example:
- The
function declaresincrement()
ascounter
to indicate that changes should apply to the global variable.global
- Each call to
modifies the globalincrement()
variable, allowing changes to persist outside the function.counter
What happens without the global
keyword?
If you attempt to assign a value to a variable inside a function without declaring it as global, Python will create a new local variable. The global variable will remain unchanged.
# Global variable
value = 5
def change_value():
value = 10 # This creates a new local variable named 'value'
print(value)
change_value() # Output: 10
print(value) # Output: 5 (the global variable remains unchanged)
Key points in the example:
- The
function creates a local variablechange_value()
that temporarily shadows the global variable.value
- The global variable
remains unaffected when you print it after callingvalue
.change_value()
Key takeaways
- Using
: Theglobal
keyword allows functions to modify a global variable.global
- Local vs. Global Scope: Without
, assigning to a variable inside a function creates a local variable that does not affect the global variable.global
- Best Practices:
- Minimize the use of global variables to avoid unintended side effects.
- Consider using function parameters and return values to pass data between functions.