Python global statement of use [turn]

When Python defined function, if you want to operate on the variables outside of the function within the function, it is necessary to declare its global within the function.

Example 1
x = 1

def func():
    x = 2

func()
print(x)

Output: 1

Not in front of the global increase in x func function, so the function func can not be assigned to x 2, can not change the value of x

 

Example 2

x = 1

def func():
    global x
    x = 2

func()
print(x)

Output: 2

Plus global, the object can be operated from outside the function within the function, its value may be changed a

 

Example 3

Global x
x = 1

def func():
    x = 2

func()
print(x)

Output: 1

 

global need to be declared within a function, if declared outside a function, the function still can not operate x

 

Transfer
Disclaimer: This article is the original article CSDN bloggers "xtingjie", and follow CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Original link: https: //blog.csdn.net/xtingjie/article/details/71210182

 

Guess you like

Origin www.cnblogs.com/paul8339/p/12089890.html