You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python运行报NameError: name 'is_zero' is not defined是哪里出错了?

报错原因

代码触发NameError的核心原因是:变量is_zero仅在if条件成立的分支中被定义,你示例中money=2.01转换为字符串后最后一位为1,不满足last_digit == "0"的判断条件,is_zero从未被赋值,后续执行print(is_zero)时就会因变量未定义抛出错误。

修复方案

提供两种可行的修复思路:

方案1:保证变量在所有执行路径下都被赋值

可以提前初始化变量默认值,也可以补充else分支,确保不管判断条件是否成立,is_zero都有定义:

money = 2.01
str_money = str(money)
last_digit = str_money[-1]
# 提前初始化默认值
is_zero = False
if last_digit == "0":
    is_zero = True
print(is_zero)

补充else分支的写法效果相同:

money = 2.01
str_money = str(money)
last_digit = str_money[-1]
if last_digit == "0":
    is_zero = True
else:
    is_zero = False
print(is_zero)

方案2:将打印操作移入if代码块

仅在is_zero被赋值的场景下执行打印逻辑:

money = 2.01
str_money = str(money)
last_digit = str_money[-1]
if last_digit == "0":
    is_zero = True
    print(is_zero)

内容的提问来源于stack exchange,提问作者Robin Groot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 23:30:02