Global variables can be defined inside the function through the global keyword. global represents a global variable, which is used to change variables outside a function; a global variable can be created by an object function or anywhere in the program; a global variable can be referenced by all objects or functions in the program.
Global variables can be defined inside the function through the global keyword.
global represents global variables. When you want to change variables outside the function in a function, you need to use the global variable global to represent
Global variables are both It can be created by a certain object function, or it can be created anywhere in this program. Global variables can be referenced by all objects or functions in this program.
global use
For list type: Change the first and last letters
newName = "xiaoming"lst4 = list(newName)def change1(): lst4 = ['g', 'i', 'a', 'o', 'm', 'i', 'h', 'x'] change1() print(lst4)def change2(): global lst4 lst4 = ['g', 'i', 'a', 'o', 'm', 'i', 'h', 'x'] change2() print(lst4)
The results are:
['x', 'i', 'a', 'o', 'm', 'i', 'h', 'g'] ['g', 'i', 'a', 'o', 'm', 'i', 'h', 'x']
For string type:
name3 = "xiaoming"def change3(): name3 = "giaominx"change3() print(name3)def change4(): global name3 name3 = "giaominx"change4() print(name3)
Result:
xiaoming giaominx
For int type:
i = 3def increase(): global i i = 4increase() print(i)
Result: 4
Summary:
1. When you want to change the variables outside the function, you need to declare the function as a global variable in the function global
2, change1 and change3 lst4 and name3 are actually not variables defined outside the function, but a new function redefined in the function
The difference between global and this
1. In Python, global refers to It is a global variable and represents the same variable only after being specified (special case: when the variable is a reference data type, it can also represent the same variable when its value is changed, such as swap1). Use
PHP中文网! !
The above is the detailed content of What keywords can be used to define global variables inside a function?. For more information, please follow other related articles on the PHP Chinese website!