如何编写Python while循环以校验两个独立用户输入?
实现双重输入校验的While循环方案
针对你的需求,我们可以通过嵌套while循环实现两次输入的校验:外层循环处理方向选择(left/right),内层循环处理湖泊通行方式选择(across/around),确保每一步输入都符合要求。
修改后的完整代码如下:
# 先定义health变量,假设初始值为100(可根据实际需求调整) health = 100 while True: first_choice = input("First choice... Left or Right (left/right)? ").lower() if first_choice == "left": # 嵌套while循环,校验湖泊选择的输入 while True: ans = input("Nice, you follow the path and reach a lake...Do you swim across or go around (across/around)? ").lower() if ans == "across" or ans == "around": # 输入正确,处理对应剧情后退出内层循环 if ans == "across": print("You managed to get across, but were bit by a fish and lost 5 health") health -= 5 print(f"Your health is now {health}") else: print("You went around and avoided getting bit by the fish, well done!") break else: print("Please enter either across or around") # 处理完left分支后退出外层循环(若需游戏持续循环可调整) break elif first_choice == "right": print("test") # 可在此添加right分支的后续逻辑,或选择退出循环 break else: print("Please enter either left or right")
代码说明:
- 外层while循环:持续接收用户的方向输入,直到输入为left或right才停止;输入错误时会提示重新输入。
- 内层while循环:仅在用户选择left时触发,专门校验湖泊通行方式的输入,只有输入across或around才会退出内层循环并处理剧情,否则一直提示用户重新输入。
- 提前定义
health变量,避免出现未定义的报错。 - 每个分支处理完后添加
break,若需要游戏持续循环,可根据需求调整break的位置。
内容的提问来源于stack exchange,提问作者Lee Howard
相关产品推荐
相关产品推荐

