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

Python报错NameError: name 'inputwhichpower'未定义的解决求助

问题原因

inputwhichpower仅在inputcattype == "fire"的条件分支中被定义。如果inputcattype不是"fire",这个变量就从未被创建,后续代码直接引用它就会触发NameError。

修复方法

方案1:嵌套条件判断

将第二个if语句放入第一个if的代码块内,确保只有变量被定义后才执行判断逻辑:

if inputcattype=="fire":
    inputwhichpower = input("Choose a power. [Fire Balls]")
    if inputwhichpower=="fire balls":
        print("Fire balls come out of nowhere and hit Slenderbot.")
        print("It took 3 Damage. It died.")

方案2:提前初始化变量

在代码开头给inputwhichpower设置默认值,避免未定义的情况:

inputwhichpower = ""
if inputcattype=="fire":
    inputwhichpower = input("Choose a power. [Fire Balls]")

if inputwhichpower=="fire balls":
    print("Fire balls come out of nowhere and hit Slenderbot.")
    print("It took 3 Damage. It died.")

额外优化建议

可以把输入转为小写,避免大小写不匹配的问题:

if inputcattype=="fire":
    inputwhichpower = input("Choose a power. [Fire Balls]").lower()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:55:19