为何if语句正常运行,else语句触发时出现NameError错误?
问题排查:NameError: name 'swim_or_wait' is not defined
错误原因
- 当你在第一个输入中选择**非"left"**的选项时,程序执行第一个
else分支,打印"Game over",但此时swim_or_wait变量根本没被定义。 - 程序不会自动停止,会继续执行后面的
if swim_or_wait.lower() == "wait"语句,找不到变量就抛出NameError。
修复方案
方案1:游戏结束后直接退出程序
在每个Game Over的分支里加入退出逻辑,避免程序继续执行后续未定义变量的代码:
import sys left_or_right = input("Choose which way you want to go. Left or right? ") if left_or_right.lower() == "left": swim_or_wait = input("Do you want to swim or wait? ") else: print("Wrong way. You fell into a hole. Game over.") sys.exit() # 退出程序,不再执行后续代码 if swim_or_wait.lower() == "wait": which_door = input("Choose which door you want to go through? Red, blue, or yellow? ") else: print("You've been attacked by a trout. Game Over.") sys.exit() # 退出程序 if which_door.lower() == "red": print("Burned by fire. Game Over.") elif which_door.lower() == "blue": print("Eaten by beasts. Game Over.") elif which_door.lower() == "yellow": print("Congratulations!!! The game is yours. You Win!") else: print("Wrong door. Game Over.")
方案2:嵌套代码分支
把依赖前面变量的代码放到对应的if分支里,确保只有变量被定义后才会执行:
left_or_right = input("Choose which way you want to go. Left or right? ") if left_or_right.lower() == "left": swim_or_wait = input("Do you want to swim or wait? ") if swim_or_wait.lower() == "wait": which_door = input("Choose which door you want to go through? Red, blue, or yellow? ") if which_door.lower() == "red": print("Burned by fire. Game Over.") elif which_door.lower() == "blue": print("Eaten by beasts. Game Over.") elif which_door.lower() == "yellow": print("Congratulations!!! The game is yours. You Win!") else: print("Wrong door. Game Over.") else: print("You've been attacked by a trout. Game Over.") else: print("Wrong way. You fell into a hole. Game over.")
内容的提问来源于stack exchange,提问作者IniaPM
相关产品推荐
相关产品推荐

