Python学习笔记五_函数的局部变量和全局变量

Python学习笔记五_函数的局部变量和全局变量

变量作用域

一个程序的所有的变量并不是在哪个位置都可以访问的,变量的作用域决定了在哪一部分程序可以访问哪个特定的变量名称。
两种最基本的变量作用域如下:局部变量和全局变量

局部变量

局部变量:在函数内部定义的变量叫做局部变量
只能在定义的那个函数里面使用,外面不可以使用

举例说明:

# print(money)  报错
def test():
	money = 100  #局部变量
	print(money)

test()
# print(money) 报错

输出结果:

100
Process finished with exit code 0

全局变量

全局变量 :在函数外部定义的变量叫做全局变量
可以在函数内部使用,可以在不同的函数之间共享

举例说明:

money = 100   #全局变量
print(money)
def test():
	print(money)

test()

print(money)

def show():
	print(money)

show()

输出结果:

100
100
100
100
Process finished with exit code 0

修改变量作用域

举例说明:

money = 100  #全局变量
def test():
    money = 10 #定义了局部变量,局部变量和全局变量重名了而已
    print(money)

test()
print(money)

输出结果:

10
100
Process finished with exit code 0

想要修改变量作用域, 需要在函数内部加global,nonlocal
全局变量名字大写 , g_money,MONEY,做区分

  1. 举例说明:global
money = 100
def test():
	# 想要修改全局变量 需要在函数内部加global
	global money
	money = 10
	print(money)

test()
print(money)

输出结果:

10
10
Process finished with exit code 0

2.举例说明:nonlocal

def fn():
	n = 100
	def inner():
		# nonlocal 可以调用上一层的作用域作用的变量
		nonlocal n  
		n += 1
		print(n)
	return inner

t = fn()

t()
t()

输出结果:

101
102
Process finished with exit code 0

对局部变量的一个保存,缺点是消耗内存

注意点

if 和 for 的作用域和外面的作用域是一样的

举例说明:

# if中的变量
if True:
	i = 1

print(i)

# for 中的变量
for value in range(4):
	print(value)

j = value + 100
print(j)

输出结果:

1
0
1
2
3
103
Process finished with exit code 0

举例说明:(会报错)

i = 1
def test():
    #global i
    i = i + 1  # i 虽然是全局变量,但是此时又重新定义了i,使得程序报错
    print(i)
test()

加上global i即可

猜你喜欢

转载自blog.csdn.net/weixin_43817580/article/details/86767129