【问题标题】:How to end a while loop using break in python?如何在python中使用break结束while循环?
【发布时间】:2021-07-30 21:11:52
【问题描述】:

我在这里写了一个循环,询问用户是否要重复一段指令。 如果他没有结束循环,则想让用户尝试三次选择他想要的(是/否)。 这是我的代码:

# Ask for repeating
i = 0
def question():
    global i
    while True:
        print("Give another try?")
        answer = input("(Y/N): ")
        answer = answer.upper()
        if answer == 'Y':
            main()
        elif answer == 'N':
            print("Thank you for participating")
            break # here it works when 'n' is typed
        else: # i count how much the while loop id repeated
            if (i < 2):
                i += 1
                question()
            else: # else is executed when i == 2
                print("don't Play with us!!")
                break # here it doesn't work.

我需要帮助。

【问题讨论】:

    标签: python if-statement while-loop global-variables break


    【解决方案1】:
    x = True
    i = 0
    def question():
        # Ask for repeating
        global i
        global x
        while x is True:
            print("Give another try?")
            answer ='a'
            answer = answer.upper()
            if answer == 'Y':
                pass
            elif answer == 'N':
                print("Thank you for participating")
                break  # here it works when 'n' is typed
            else:  # i count how much the while loop id repeated
                if (i < 2):
                    i += 1
                    question()
                else:  # else is executed when i == 2
                    print("don't Play with us!!")
                    x = False  # here it doesn't work.
    

    【讨论】:

      【解决方案2】:

      在最后一个 else 块之外添加另一个中断。你的代码应该是

      i = 0
      def question():
          global i
          while True:
              print("Give another try?")
              answer = input("(Y/N): ")
              answer = answer.upper()
              if answer == 'Y':
                  main()
              elif answer == 'N':
                  print("Thank you for participating")
                  break # here it works when 'n' is typed
              else: # i count how much the while loop id repeated
                  if (i < 2):
                      i += 1
                      question()
                  else: # else is executed when i == 2
                      print("don't Play with us!!")
                      break # here it doesn't work.
                  break
      

      【讨论】:

      • 哦,这是我的错:break 应该在第二个“else”之外。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      • 1970-01-01
      • 2016-06-14
      • 1970-01-01
      • 1970-01-01
      • 2018-06-13
      相关资源
      最近更新 更多