Python global

BrandonDusch's avatar
Published Jul 30, 2022
Contribute to Docs

The global keyword creates or references a global variable that can be updated within the scope of a function or class.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours

Syntax

variable = initial_value

def function_name:
  global variable
  # ...

class ClassName:
  global variable

  def example_method:
    global variable
    # ...

The snippet above showcases the various places that a variable can be referenced with the global keyword.

Note: The variable must not be defined and set within the function/class scope before being referenced with the global keyword. Otherwise, an error will occur.

Codebyte Example

The following is an example of the global keyword being used in an increment() function:

Code
Output

All contributors

Contribute to Docs

Learn Python on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
    • With Certificate
    • Beginner Friendly.
      24 hours