【问题标题】:Python - "break" statement breaking outside loopsPython - 打破外部循环的“break”语句
【发布时间】:2018-06-21 15:57:39
【问题描述】:

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

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

【问题讨论】:

  • 函数怎么用?

标签: python loops


【解决方案1】:

您的外部 while 循环具有条件 while i &lt; 5,但您的 break 语句发生在 i 为 7 时... 987654326@外循环也结束了。

【讨论】:

    【解决方案2】:

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

    确保在第二次运行游戏之前适当地重置i。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 1970-01-01
      • 2016-05-12
      相关资源
      最近更新 更多