Python寻宝游戏中如何正确结束if else语句避免代码继续执行?
问题原因
你的代码里三组条件判断是完全平级的关系,哪怕前面已经触发了Game Over逻辑,程序也不会终止,还会继续执行后续的输入询问代码,甚至当你第一步选了right或者无效选项时,wait_or_swim变量根本没有被定义,运行到第二个判断块的时候还会直接触发变量未定义的报错。
修复方案
推荐用嵌套判断的写法,把后续步骤的逻辑全部封装到前一步选择正确的分支内,只要选错就不会进入后续逻辑,天然不会执行多余的代码,修改后代码如下:
print('Welcome to the Treasure Hunt!') print('Your goal is to find the treasure.') direction = input('You are at a crossroad. Where do you want to go? Type "left" or "right". \n').lower() if direction == "left": wait_or_swim = input('You have come to a lake. There is an island in middle of the lake. Type "wait" to wait for a boat or "swim" to swim accross the lake? \n').lower() if wait_or_swim == "wait": color = input('You arrived at the island unharmed. There is a house with three doors. One red, one blue and one green. Which one will you choose? \n').lower() if color == "red": print('You fell into a room full of fire.\nGame Over.') elif color == "green": print('Congratulations, you have found the treasure!') elif color == "blue": print('You fell into a ditch.\nGame Over.') else: print('You chose a door that does not exist.\nGame Over.') elif wait_or_swim == "swim": print('You have been eaten by a shark.\nGame Over.') else: print('You chose an option that does not exist. ') elif direction == "right": print('You are crushed by a truck. Game Over!') else: print('You chose an option that doesn\'t exist.')
如果你不想调整原有代码的结构,也可以在每一个Game Over的打印语句后加一行exit()直接终止程序运行,同样能实现需求。
内容的提问来源于stack exchange,提问作者Prab-mat
相关产品推荐
相关产品推荐

