In Python, there are some special places for referencing global variables. Let's look at the code example.
def Test (): ... Print num ... = num+1 ... Print Value ... >>> Test (12)
The above code defines a global variable, num, so we can use the global variable within the function.
But if we want to modify the global variables inside the function, the notation is special, such as:
def Test (): ... Num=2 ... Print num ... >>> Test ()2>>> num1
As you can see, the num=2 operation inside the function does not operate on global variables, but instead produces a new local variable. has no effect on global variables.
In some cases, there will be an error, such as:
def Test (): ... Num=num+1 ... >>> Test () Traceback (most recent call last): '<stdin>'in <module> "<stdin>"in ' Num ' referenced before assignment
From the information of the error, in the test function, Num still as a local variable, but because there is no assignment before the reference, so error.
To refer to global variables within a function, it is a good practice to refer to them first through the global keyword, such as:
def Test (): ... Global num ... Num=num+1 ... Print num ... >>> Test ()2>>> num2
As you can see, the Global keyword can be used within a function after it is identified.
Of course, we need to emphasize that, normally in application development, we should avoid using global variables, which is explained from a grammatical point of view.
Local variables and global variables for Python