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
相关产品推荐
相关产品推荐

