python基础之全局变量

import random # 导入模块包

print(random.random()) # 随机生成0-1之间的浮点数

print(random.randint(1, 10)) # 随机生成指定范围内的整数

li = [‘a’, ‘b’, ‘c’, ‘d’]

print(random.choice(li)) # 随机获取一个元素

random.shuffle(li) # 将列表中的元素随机排列

print(li)

def test():
name = ‘周凯’ # 局部变量,函数外部无法使用
print(name)

test()

def test2():
name = ‘未来可期’ # 局部变量
print(name)

test2()

1.2 全局变量

a = ‘爱你摸摸哒’
print(f’函数外的a :{a}’)

def funb():
a = ‘黄乐强’
print(f’函数内的a:{a}’)

funb()

总结: 函数内部如果使用一个变量,会先从内部找,有则使用,无则用全局,全局没有就报错.

修改全局变量

a = 10

def fund():
global a # 声明全局变量
a = 20
print(‘函数内的a:’, a)

print(‘函数外的a的值’, a)
fund()
print(‘函数外的的a :’,a)

3.nonlocal

nonlocal 只能用于嵌套函数中,声明变量只对局部起作用

nonlocal 对最近一层局部作用于寻找局部变量

y = 10

def outer():
y = 20

def inner():
    nonlocal y
    print('inner函数中的y :', y)
    y = 30

print('调用inter函数前,outer函数中的y :', y)
inner()
print('调用inter函数后,outer函数的y :',y)

outer()

总结:

global() 将局部变量变成一个全局变量

nonlocal 在内层中函数函数中修改函数的变量(非全局变量)

猜你喜欢

转载自blog.csdn.net/qq_36048693/article/details/115315600