global
In Python, the global
keyword lets you declare that a variable used inside a function is global. This allows you to modify the variable outside of the current function scope. The global
keyword is essential when you need to work with variables that exist outside the local scope of a function.
Python global
Keyword Examples
Here’s a quick example to demonstrate how you can use the global
keyword:
>>> number = 10
>>> def modify_number():
... global number
... number = 42
...
>>> modify_number()
>>> number
42
In this example, the variable number
is defined in the global scope with an initial value of 10
. The function modify_number()
declares number
as global, allowing you to modify the global variable number
to 20
. After calling modify_number()
, accessing number
returns 42
, showing that the global variable was modified.
Python global
Keyword Use Cases
- Modifying global variables from within a function
- Sharing and updating state across different functions or modules
- Managing configuration settings that need to be accessed and modified globally
Related Resources
Tutorial
Using and Creating Global Variables in Your Python Functions
In this tutorial, you'll learn how to use global variables in Python functions using the global keyword or the built-in globals() function. You'll also learn a few strategies to avoid relying on global variables because they can lead to code that's difficult to understand, debug, and maintain.
For additional information on related topics, take a look at the following resources:
- Variables in Python: Usage and Best Practices (Tutorial)
- Namespaces and Scope in Python (Tutorial)
- Python Scope & the LEGB Rule: Resolving Names in Your Code (Tutorial)
- Working With Global Variables in Python Functions (Course)
- Using and Creating Global Variables in Your Python Functions (Quiz)
- Variables in Python (Course)
- Variables in Python: Usage and Best Practices (Quiz)
- Navigating Namespaces and Scope in Python (Course)
- Namespaces and Scope in Python (Quiz)