我已经有一个工作的 while 循环
while True: do_youwanttoplay = input("Do you want to play? ").lower() if do_youwanttoplay == "yes": print ("You are starting with", health, "health") print ("Let's play!") break elif do_youwanttoplay == "no": print ("Cya...") break else: print ("Please enter either yes or no")
但是对于下一个代码块,我希望它检查用户是否输入了“是”或“否”(它目前正在输入),并检查用户是否输入了“跨”或“周围”
while True: first_choice = input("First choice... Left or Right (left/right)? ").lower() if first_choice == "left": ans = input("Nice, you follow the path and reach a lake...Do you swim across or go around (across/around)? ") break elif first_choice == "right": print("test") else: print ("Please enter either left or right") if ans == "across": print ("You managed to get across, but were bit by a fish and lost 5 health") health -= 5 print ("Your health is now", health) elif ans == "around": print ("You went around and avoided getting bit by the fish, well done!")
你的代码存在一些缩进错误,导致第二个代码块无法正常运行。在 Python 中,缩进对于定义代码块的范围非常重要。下面是已经修复了缩进错误的代码:
while True: do_youwanttoplay = input("Do you want to play? ").lower() if do_youwanttoplay == "yes": print("You are starting with", health, "health") print("Let's play!") break elif do_youwanttoplay == "no": print("Cya...") break else: print("Please enter either yes or no") while True: first_choice = input("First choice... Left or Right (left/right)? ").lower() if first_choice == "left": ans = input("Nice, you follow the path and reach a lake... Do you swim across or go around (across/around)? ") break elif first_choice == "right": print("test") else: print("Please enter either left or right") if ans == "across": print("You managed to get across, but were bit by a fish and lost 5 health") health -= 5 print("Your health is now", health) elif ans == "around": print("You went around and avoided getting bit by the fish, well done!")
现在,第一个循环和第二个循环都能够正常运行,并根据用户的输入执行相应的代码逻辑。在第二个循环中,根据用户的第一个选择,要么询问第二个问题,要么执行其他操作。请确保根据你的需求对代码进行进一步的调整和扩展。