python基础:局部变量--全局变量的使用

局部变量:

使用原则:仅在本函数内部使用的变量,其他函数无法使用本函数的变量

代码:

def function1():
a = 2 #定义一个局部变量
print(a)

def function2():
print(a) #该变量无法使用function1函数定义的局部变量a

function1()
function2()

打印结果:

2
Traceback (most recent call last):
File "day1.py", line 44, in <module>
function2()
File "day1.py", line 41, in function2
print(a)
NameError: name 'a' is not defined

全局变量:

使用原则:在函数外部定义的变量,在所有函数中都可以进行调用

代码:

# 定义一个全局变量

a=100

def test1():
a = 2
print(a)


def test2():
print(a)

test1()
test2()

打印结果:

2

100

在函数内部中可修改全局变量

代码:

wendu = 0
def test3():

global wendu # 使用global关键字,在test3函数内部,定义的这个wendu=100为全局变量
wendu = 100
print(wendu)

def test4():

print(wendu) #此时使用的是全局变量


test3()
test4()

打印结果:

100

100

原文地址:https://www.cnblogs.com/yangsun/p/11055655.html