Skip to content

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:

Language: 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 42. After calling modify_number(), accessing number returns 42, showing that the global variable was modified.

Step through the example to see which scope each line binds number in, then switch to Without global to watch the same assignment play out with the global number line removed:

Interactive diagram — enable JavaScript to view.

With global number, the assignment rebinds the name in the global scope, so number reads 42 after the call. Without it, number = 42 creates a separate number in the function’s local scope. That name disappears when the function returns, and the global number stays 10.

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
Using and Creating Global Variables in Your Python Functions

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:

Have a question about this? Mentor AI can show you examples, compare related terms, and point you to tutorials.


By Leodanis Pozo Ramos • Updated Oct. 20, 2026 • Reviewed by Dan Bader