The Global keyword in Python

Tram Ho

Hello everyone in this article, I will introduce you to Global Keywords in Python, I will explain to you what their concept is, their syntax and how to use them. You can find out in my article!

What is the Global Keyword.

In Python, the Global keyword allows you to modify a variable outside of the current range. It is used to create a global variable and make changes to that variable in the local context.

The rules of the Global keyword.

The basic rules for the Global keyword in Python are:

  • When we create a variable inside a function, it will be local by default.
  • When we define a variable outside of a function, it is global by default. You don’t need to use Global keywords.
  • We will use the Global keyword to read and write a global variable inside a function.
  • Note that using the Global keyword outside of a function won’t work.

Use global keywords.

I will have a few examples.

Example 1: Accessing the Global variable from within a function

When I run the above program, the output will be:

However, we may encounter some situations where it is necessary to modify a global variable from within a function.

Example 2: Modify the global variable from within the function

When I run the above program, an error will occur:

This is because we can only access the global variable but cannot modify it from within the function. So the solution given will be I will use the keyword Global .

Global variables in Python modules

In Python, we will create a module to hold Global variables and share information across Python modules in the same program.

This is how one can share Global variables across python modules.

Example 3: Sharing a Global variable across Python modules

Create one file to store variables Global .

Create an file to change the Global variables.

Create a file to check for value changes

Above, we have created three files: , and

The module stores the global variables of a and b In the file, we import the module and modify the values ​​of a and b . Similarly, in the file, we import both the modules and . Finally we print and check the values ​​of the Global variables to see if they have been changed.


Here I have introduced to you about the concept of Từ khóa Global , uses and some examples of using Global Keyword in Python. Hope you enjoyed this article. If you have any questions, please leave a comment below.

See more details

Share the news now

Source : Viblo