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:

Python
>>> 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

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.

intermediate best-practices python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 6, 2025 • Reviewed by Dan Bader