Python 如何让 if/elif 的不同分支继续执行同一段剧情?
数据小许
可以实现。把丛林剧情改成独立的 if,并在玩家选择 run 或 leave 时将 cave_or_jungle 设为 "jungle",这些路线就会进入同一段丛林剧情。
为什么原来的 elif 不会执行?
同一组 if/elif/else 只会执行一个分支。最外层的 if cave_or_jungle == "cave": 成立后,程序会执行洞穴分支,跳过同组剩余的 elif,然后继续执行整组条件语句后面的代码。
即使在洞穴分支里把 cave_or_jungle 改成 "jungle",同组的 elif 也不会重新判断。
另外,贴出的代码缺少缩进。如果实际文件也是这样,程序会先报缩进错误。下面的示例补齐了各分支的缩进。
用独立 if 衔接丛林剧情
需要做两处修改:
- 在
run和leave分支中设置cave_or_jungle = "jungle"。 - 将最外层的
elif cave_or_jungle == "jungle":改成独立的if,与洞穴的if保持相同缩进。
完整示例:
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.")
cave_or_jungle = "jungle"
elif deeper_or_leave == "leave":
print("You go back outside.")
cave_or_jungle = "jungle"
if 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?")
第二个 if 会根据 cave_or_jungle 的当前值重新判断:
- 一开始选择
jungle:跳过洞穴代码,直接进入丛林。 - 进入洞穴后选择
leave:变量更新为"jungle",随后进入丛林。 - 深入洞穴后选择
run:变量更新为"jungle",随后进入丛林。 - 选择
fight:输出失败信息,变量仍为"cave",不会进入丛林。
是否需要 break 或 return?
这里不需要额外的退出语句。执行完条件分支后,Python 会继续执行整组条件语句之后的代码。
break 用于退出 for 或 while 循环,不能单独用来退出 if。return 用于退出当前函数,也不会跳转到后面的 elif。
要注意,print("GAME OVER") 只是输出文字,# Game ends 只是注释,两者都不会主动终止游戏。上面的示例在失败后不会进入丛林分支,随后到达脚本末尾。如果以后在后面追加其他剧情,需要另行安排结束逻辑,例如将游戏放进函数,并在失败分支使用 return。
当前示例没有处理无效输入。输入不匹配任何分支时,相应分支会被跳过;如果需要重新提示玩家,可以加入输入校验循环。
备注:内容仅供参考。
