首页 > 解决方案 > 当我运行解码代码时,循环继续上一个问题

问题描述

我正在尝试使用while循环在python中进行文本游戏挑战,但是当我完成游戏时,它仍然会继续上一个问题,我希望它在用户回答最后一个问题时停止。

question = ""


while question.lower() != "yes" and question.lower() != "no":
    question = input("Do you want to play?\n")
    print()
    if question.lower() == "yes":

        while question.lower() != "bottle" and question.lower() != "castle":
            question = input(f"You are alone in a island and you saw a BOTTLE and a CASTLE\n Which one do you choose?\n ")
            print()
            if question.lower() == "bottle":
                                
                while question.lower() != "sea" and question.lower() != "trees":
                    question = input("The bottle has a message: \"No one leaves this island without proving their worth to themselves\", you can try the SEA or the TREES\n Which one do you choose\n")
                    print()
                    if question.lower() == "sea":
                        print("Is already night, and you were ate by a whale \U0001F40B in the blink of an eye")
                        print()
                        break
                    else:

……

    elif question.lower() == "no":
        print("That´s too bad!")
        print()
    else:
        print("Invalid answer, please try again")
        print()

标签: pythonloopswhile-loop

解决方案


导入 sys 并使用 sys.exit() 代替 break 语句。代码不起作用,因为这些 break 语句只中断内部 while 循环而不是外部循环。


推荐阅读