Touch python time is not long, some knowledge points, not very solid grasp, I personally advocating no matter what things to learn, first of all must go back to the foundation to play very solid, and then go higher. Today, I encountered a global variable in Python operation, encountered a problem, so, here will be the problem, make a record, with a long mind!!!
The use of global variables in Python, in fact, is not a very sensible choice, but you still believe that existence is reasonable, is how you use; Global variables reduce commonality between modules and functions; Therefore, in future programming, you should avoid using global variables as much as possible.
Use of global variables:
Method One:
In order to facilitate the code management, the global variable is unified into a module, then the global variable is imported, and the global variable module is used in this way.
To define a global variable in a module:
Copy Code code as follows:
#global. py
Global_1 = 1
Global_2 = 2
Global_3 = ' Hello world '
Then import the global variable definition module in a module and use global variables in the new module:
Copy Code code as follows:
Import Globalvalues
Def printglobal ():
Print (Globalvalues.global_1)
Print (Globalvalues.global_3)
Globalvalues.global_2 + 1 # Modify values
if __name__ = = ' __main__ ':
Printglobal ()
Print (globalvalues.global_2)
Method Two:
Define the global variable directly in the module and use it directly in the function OK. However, when using global variables, you must identify them using the global keyword in the function:
Copy Code code as follows:
CONSTANT = 0
Def modifyglobal ():
Global CONSTANT
Print (CONSTANT)
CONSTANT + 1
if __name__ = = ' __main__ ':
Modifyglobal ()
Print (CONSTANT)
!!!, finish the lecture.