Table of Contents
This guide covers global keywords in python with practical context and easy-to-follow details. Use it to understand the subject and apply the information confidently.
In the last Python variable, when I mentioned the problem of changing the value of the global variable in a function, I said I must use the Python keyword asglobal, but I didn't say how to use it because I wanted to set aside a article to write. Details about this keyword.
In Python, theglobalKeyword allows you to edit variables outside the current scope. It is used to create global variables and make changes to variables in the local context.
Rules of Global Keywords in Python
- When we create variables in a function, it defaults to local variables.
- When we define a variable outside the function, it defaults to global variables. You do not need to use global keywords.
- We use the
globalKeyword to read and write global variables in a function. - Using the
globalKeyword outside a function does not work at all.
Using Global Keywords in Python
Example 1: Access global variables from within a function
a = 1 # Bi?n toàn c?cdef them():print(a)them()
When we run the above code, we get the output of 1. However, there are some cases where we need to modify the global variable from within the function, which is the case I mentioned from the beginning, so what to do?
Example 2: Modifying global variables in a function
Suppose we need to edit the value of a to a + 9 in thethem()Function, if we write the following code:
a = 1 # Bi?n toàn c?cdef them():a = a + 9 print(a)them()
You will receive an error message:
UnboundLocalError: bi?n bi?n 'm?t' ? ??a ch? tr??c khi giao d?ch
That's because we can only access global variables and cannot edit them in a function. The solution to this problem is to use theglobalKeyword. Then, the above code will be rewritten as follows:
a = 1 # Bi?n toàn c?cdef them():global a a = a + 9print("Trong them():", a)them() print("Trong main:", a)
Running the above code we get the output as:
In addition (): 10 In main: 10
Here, we define a as a global variable in thethem()Function, then increase the value ofaTo 9, iea = a + 9. Then, we call thethem()Functionthem(), finally, print global variablesa. As a result, changes made to the variable a in thethem()Functionthem()Also occur on the global variable outside the function, a = 10.
Example 3: Share global global variables via modules in Python
In Python, we create a dun config. Py to hold global variables and share information through Python modules in the same program. This is how we can share global variables through Python modules.
Create a config. Py file to store global variables:
a = 0 b = "empty"
Create an update. Py file to change global variables:
import config config.a = 10 config.b = "TipsMake.com"
Write the main. Py file to check for changes:
import config import update print (config.a) print (config.b)
When running main. Py file, the output will be:
ten TipsMake.com
Here, we have created 3 files, config. Py, update. Py and main. Py. The config. Py module stores two global variables,aAndb. In the update. Py file we enter the module config. Py and modify the value of the variablea, b. Similar to the main. Py file, enter both modules config. Py and update. Py. Finally, we use the print command to check if the values of variables a and b have been changed.
Example 4: Use global variables in nested functions.
In this example you will know how to use global variables in nested functions.
def ham1 ():
x = 20
def ham2 ():
global x
x = 25
print ("Before calling ham2:", x)
print ("Calling ham2")
ham2 ()
print ("After calling ham2:", x)
ham1 ()
print ("x in main:", x)
Running the above code we can:
Before calling ham2: 20 Calling ham2 After calling ham2: 20 x in main: 25
Here, we declare the global variable in the nest functionham2(). Inham1(),xNot affected byglobalKeywords.
Before and after callingham2(),xWill take the value of the local variable20. Outside theham1(), xFunctionham1(), xWill take the global value, reported inham2()25. This is because we use theglobalKeyword inxTo create global variables inham2(). If we make any changes toxinham2(), the change appears outside the local scope.
Do a Python exercise with a prize to practice more.
Next lesson: Module in Python
Previous post: Global variable (global), local variable (local), nonlocal variable in Python
FAQ
What should I check before following these steps?
Confirm device and software compatibility, save important data, and make sure you have the required permissions, files, and account access.
Why might the process not work?
Common causes include outdated software, missing permissions, incompatible hardware, an unstable connection, or completing a step in the wrong order.
Can I undo the changes if necessary?
That depends on the tool or setting. Use built-in restore options when available, keep a backup, and record the original configuration first.
Reader Comments 0
Sign in with email or Google to join the discussion.