Python中if/elif语句退出后继续执行代码的问题
问题
我正在编写一款文本类游戏练习if/elif语句,现在遇到了执行流程的问题:当玩家从洞穴分支选择「离开」或者「逃跑」后,程序执行完当前语句就停止了,但我希望这两个分支执行完毕后,能直接衔接丛林分支里的后续剧情(也就是询问跟随河流还是烟雾的部分),请问该怎么实现?
现有代码
cave_or_jungle = input("Do you go into the JUNGLE or the CAVE?").lower() if cave_or_jungle == "cave": print("You go into the cave! The cave is cold and dark. You find a rusty lantern and hear strange growling deeper inside.") deeper_or_leave = input("Do you go DEEPER or LEAVE?").lower() if deeper_or_leave == "deeper": print("Deep in the cave, a giant beast jumps out of the darkness.") fight_or_run = input("Do you FIGHT or RUN?").lower() if fight_or_run == "fight": print("The beast is too powerful. You are defeated.") print("GAME OVER") # Game ends elif fight_or_run == "run": print("You run back outside and follow the jungle path.") # 希望从这里继续执行丛林分支的后续代码 elif deeper_or_leave == "leave": print("You go back outside.") # 希望从这里继续执行丛林分支的后续代码 elif cave_or_jungle == "jungle": print("You are in the jungle!") print("The jungle is thick and noisy. You hear water nearby and see smoke rising through the trees.") input("Do you follow the RIVER or the SMOKE?")
解决方法
直接把丛林分支的后续剧情抽出来做成独立的函数,这样不管是一开始选丛林,还是从洞穴返回,都可以调用这段剧情,不用硬跳转elif分支:
修改后的完整代码
# 把丛林后续剧情封装成函数 def jungle_story(): print("You are in the jungle!") print("The jungle is thick and noisy. You hear water nearby and see smoke rising through the trees.") input("Do you follow the RIVER or the SMOKE?") cave_or_jungle = input("Do you go into the JUNGLE or the CAVE?").lower() if cave_or_jungle == "cave": print("You go into the cave! The cave is cold and dark. You find a rusty lantern and hear strange growling deeper inside.") deeper_or_leave = input("Do you go DEEPER or LEAVE?").lower() if deeper_or_leave == "deeper": print("Deep in the cave, a giant beast jumps out of the darkness.") fight_or_run = input("Do you FIGHT or RUN?").lower() if fight_or_run == "fight": print("The beast is too powerful. You are defeated.") print("GAME OVER") elif fight_or_run == "run": print("You run back outside and follow the jungle path.") jungle_story() # 调用丛林剧情 elif deeper_or_leave == "leave": print("You go back outside.") jungle_story() # 调用丛林剧情 elif cave_or_jungle == "jungle": jungle_story() # 调用丛林剧情
为什么这么做
- 避免重复写相同代码,后续修改丛林剧情时,只需要改动函数内的内容即可
- 逻辑更清晰,调用函数就能直接衔接剧情,不用纠结如何跳转到原elif分支里
内容的提问来源于stack exchange,提问作者Haunt
相关产品推荐
相关产品推荐

