python -- global

本文通过一个Python编程实例,探讨了局部变量与全局变量的引用问题,特别是在函数内修改全局变量时遇到的UnboundLocalError错误。通过单步调试,详细解释了错误原因,并提供了正确的解决方案,即使用global关键字声明全局变量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

写了个小例子练手,报错:

Traceback (most recent call last):
File “game.py”, line 74, in < module >
update_total(True, 10) File “game.py”, line 70, in update_total
total = total + num
UnboundLocalError: local variable ‘total’ referenced before assignment

代码如下:

total = 200
def update_total(is_add, num):
    if is_add:
        total = total + num
    else:
        total = total - num

update_total(True, 10)
print('total = ' + str(total))

为啥呢?
单步调试进去,发现在函数内部是可以访问函数外部定义的total变量的

E:\code\python>python -m pdb game.py
e:\code\python\testcode\game.py(3)()
(Pdb) b 74
Breakpoint 1 at e:\code\python\testcode\game.py:74
(Pdb) c
e:\code\python\testcode\game.py(74)()
-> update_total(True, 10)
(Pdb) s
–Call–
e:\code\python\testcode\game.py(68)update_total()
-> def update_total(is_add, num):
(Pdb) s
e:\code\python\testcode\game.py(69)update_total()
-> if is_add:
(Pdb) n
e:\code\python\testcode\game.py(70)update_total()
-> total = total + num
(Pdb) total
200
(Pdb) total + num
210

(Pdb) n
UnboundLocalError: “local variable ‘total’ referenced before assignment”
e:\code\python\testcode\game.py(70)update_total()
-> total = total + num
(Pdb)

函数内部可以访问total变量,total = total + num却会出错,说明问题出现在了赋值语句上
当然通过报错信息也直接说明了问题出现在赋值语句上

查询python文档,找到global的使用:

The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. It would be impossible to assign to a global variable without global, although free variables may refer to globals without being declared global.

global语句是针对当前整个代码块的声明。这意味着列在其后的所有标识符将被解析为全局有效的。不用global给全局变量赋值是不可能实现的,尽管自由变量可以引用全局变量而不用声明为全局的。

所以修改为:

在total变量赋值前,声明total是全局变量即可

total = 200
def update_total(is_add, num):
    global total
    if is_add:
        total = total + num
    else:
        total = total - num
update_total(True, 10)
print('total = ' + str(total))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值