Python-打破外部循环的“ break”语句

时间:2018-06-21 15:57:40

标签: python loops

当用户完成游戏操作(回答所有问题)后,游戏应该中断游戏循环并返回密码提示,但它会中断整个程序循环,而游戏会在循环结束时结束该程序。 有任何想法吗?

access = 1
score = 0

print("Hello, user.\n")

while i < 5:

    input1 = input("Enter Password:\n")

    if input1 == password:
        print("Access Granted\n\n-----------------------------\n")


        r2 = input("Enter 1: Play 20 Questions\nEnter 2: Change your password\nEnter 3: Decrypt a message\nEnter 4: Encrypt a Message\nEnter 5: Exit Terminal\n\n")

        #20 Questions
        while r2 == "1" and access == 1:


            questions = ["Who was the first president of the United States?", "what is the USA's biggest state?", "What USA city has the most tourism?", "Where are most tech companies located?"
                     , "how many branches of the military are there?", "how many states are in the US", "When was the Decleration of Independence signed?", 
                     "What form of government is the USA?", "", "", ""]
            answers = ["george washington", "alaska", "new york", "silicon valley", "5", "50", "1777", "Constitutional Republic"]


            print(questions[i])
            answer = input("")

            #If answer is correct
            if answer == answers[i]:
                score += 1
                print("Correct! your score is now")
                print(score)
                i += 1

                if i == 7:
                    break
            else:
                print("Wrong, your score is still")
                print(score)
                i += 1

                if i == 7:
                    break

    else:
        print("\nAccess Denied\n")
        i += 1

        if i == 5:
            print("You have run out of attempts.")
            access = 2
        continue

2 个答案:

答案 0 :(得分:0)

当您的代码到达break语句时,您将拥有i=7,因此,当Python重新评估主循环的条件时,它将为false。看来您应该让它成为一个简单的while True循环,以便您的break语句具有预期的效果。

在再次运行游戏之前,请确保适当重置i

答案 1 :(得分:0)

您的外部while循环的条件为while i < 5,但是当i7时,您的break语句就会发生... break关键字正在脱离内部循环,但由于i不是< 5,因此外部循环也会结束。