Scope declaration of python function variables (global and local variables) - reprint

See a good anne's summer article to share
Scope declaration of function variables (global and local variables)
Introduce questions:

Local variables:
Local variable: a variable defined inside a function. Its scope is limited to the inside of the function. It cannot be used outside the function.

For example:

#encoding = utf-8

def demo():

    tips = "No Smoking"

    print("Function internal variable tips:",tips)

demo()

print ("Function external variable tips:",tips) 

You can see that if you try to access a variable defined inside a function outside the function, you will report an error of NameError

global variable
1. Global variable: a variable defined outside a function. The scope is the whole program. It can be used outside the function or inside the function.

2. For internal use, global needs to be declared as a global variable.

3. When used internally, if you do not want to affect global variables, you declare them as local variables.

For example:

#encoding = utf-8

tips = "No Smoking"

def demo():

    print("Function internal variable tips:",tips)   #Global variables are referenced only inside functions

demo()

print ("Function external variable tips:",tips)

If you modify the global variable inside the function at this time, an error will be reported as follows:

#encoding = utf-8

tips = "No Smoking"

def demo():

    tips+="!"   #Modify global variables

    print("Function internal variable tips:",tips)

demo()

print ("Function external variable tips:",tips)

reason:

The python interpreter mistakenly regards tips as a local variable, and there is no definition of tips inside the function, so an error is reported. If the internal scope wants to change the value of the external scope, you need to add global.

resolvent:

1) The tips variable is declared globally within the function (using global). This method will change the value of the global variable tips synchronously.

2) Define a local variable to store the modified value. tips is only modified inside the function.

3) Define the same tips as the global variable in the function. Tips will only be modified inside the function.

#Modification method 1:

#encoding = utf-8

tips = "No Smoking"

def demo():

    global tips   #Using global

    tips+="!"

    print("Function internal variable tips:",tips)

demo()

print ("Function external variable tips:",tips)

Modification method 2:

#encoding = utf-8

tips = "No Smoking"

def demo():

    new_tips = tips + "!"  #Assign the modified tips value to the new variable

    print("Function internal variable new_tips:",new_tips)

demo()

print ("Function external variable tips:",tips)

 

 

Modification method 3:

#encoding = utf-8

tips = "No Smoking"

def demo():

    tips="No Smoking"    #Declare as a local variable

    tips+="!"

    print("Function internal variable tips:",tips)

demo()

print ("Function external variable tips:",tips)

 

 

Take another example:

List = [1,2,3]

String = "hello"

def demo():

    String = "hi"

    List[0] = "*"

    print("Function internal variable List:",List)

    print("Function internal variable String:",String)

demo()

print("Function external variable List:",List)

print("Function external variable String:",String)

Question: why is a global variable list defined? When it is modified inside the function, there will be no error without adding global?

reason:

1) For String = "hello" in the function, it is "ambiguous" because it can be either a String representing a reference to a global variable or a new local variable. Therefore, in python, its default behavior is to create a local variable unless global is explicitly declared.

2) For the List[0] = "*" in the function, it is "explicit", because if the List is regarded as a local variable, it will report NameError, so it can only refer to the global List, so there is no need to declare the global explicitly.

3) If the List variable in the function is written as List = ["*"], the List will also become a local variable

4) If you think about it carefully, you will find that more than list does not need global, All "explicit" things do not need a global. Because there is only one modification method, such as int type and str type, that is, x = y. it happens that this modification method is also a method to create variables, so it is ambiguous whether to modify or create. dict/list / object can be modified by dict ['x '] = y or list.append() Such modifications do not conflict with the creation of variables and do not produce ambiguity, so there is no need for explicit global

Therefore, it solves the initial problem of why the string should be declared as a global variable inside the function instead of the list.

Summary:
1) Global variables are referenced without golbal declaration

2) Global declaration is required to modify global variables,

3) In particular, if variable types such as lists and dictionaries only modify the value of elements in them, they can directly use global variables without global declaration.

Recommendations:
1) If you want to use an external global variable in a function, write it as global

2) If you do not want to use external global variables, initialize the variables within the function (that is, declare local variables).

Keywords: Python Back-end

Added by paulspoon on Thu, 27 Jan 2022 01:18:10 +0200