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

Python Try-Except块内变量作用域问题:NameError原因解析

NameError: name 'x' is not defined 原因分析

初始可用代码

while True:
    try:
        x = int(input("what's x? "))
    except ValueError:
        print(f"x is not an integer!")
    else:
        break

print(f"x is {x}")

修改后报错的代码

while True:
    try:
        x = int(input("what's x? "))
    except ValueError:
        print(f"{x} is not an integer!\nPlease enter an integer.....")
    else:
        break

print(f"x is {x}")

触发的错误

NameError: name 'x' is not defined.

错误根源

  • 当输入内容无法转换为整数时,代码会触发ValueError并进入except代码块。
  • 初始代码的except块里,print的是固定字符串,其中的x只是普通文本,不需要访问变量。但修改后的代码用了f-string,{x}会让Python去查找名为x的变量。
  • 核心问题:如果第一次输入就失败,try块里的x = int(...)根本没执行成功,变量x从未被定义。因为转换失败时会直接跳转至except,赋值语句没有完成,自然找不到x这个变量。
  • 初始代码能正常运行是因为:只要用户最终输入有效整数,else块会执行break,此时x已经被成功定义,最后打印的x是有效的。但修改后的代码在第一次输入错误时就会尝试访问未定义的x,直接抛出错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 05:47:34