【问题标题】:Trying to exit the program, get endless loop (Python)试图退出程序,得到无限循环(Python)
【发布时间】:2020-08-10 19:30:24
【问题描述】:

我是一个初学者,试图退出我在 Python 中的第一个程序,但只是陷入无限循环。 不明白出了什么问题。

question = input("Please enter your 'to do' list: ")
some_list = []

while True:
    if question not in some_list:
        some_list.append(question)
        question = input("Please enter your 'to do' list: ")
    else:
        print("\n\nPress enter to exit")
        print(some_list)

【问题讨论】:

  • 使用break退出while循环
  • 您已将预定义名称 list 用于可能导致程序崩溃的变量。在获得问题输入后使用 break

标签: python loops infinite-loop exit


【解决方案1】:

欢迎! 如果您想像您在其中一个打印件中所写的那样打破循环:“\n\nPress enter to exit”,您可以使用以下解决方案:

while True:
  x = input()
  if len(x) == 0:
    break

完整的代码是:

question = input("Please enter your 'to do' list: ")
list = []

while True:
    question = input("Please enter your 'to do' list: ")
    if len(question) == 0:
        break
    if question not in list:
        list.append(question)

print(list)

【讨论】:

    【解决方案2】:

    首先,永远不要使用内置函数作为变量。您基本上将数字 4 分配给数字 5:4=5。这是错误的。我在那里修好了。

    question = input("Please enter your 'to do' list: ")
    
    something = []
    
    
    while True:
        if question not in something:
            something.append(question)
            question = input("Please enter your 'to do' list: ")
        else:
            print("\n\nPress enter to exit") 
            print(something)
    

    `

    【讨论】:

      【解决方案3】:
      question = input("Please enter your 'to do' list: ") 
      alist = []
      
      while True:
          if question not in alist:
              alist.append(question)
              question = input("Please enter your 'to do' list/type 'quit' to exit: ")
              if question=='quit': 
                  break
      print(alist)
      

      【讨论】:

        【解决方案4】:
        question = input("Please enter your 'to do' list: ")
        list = []
        
        while True:
            if question not in list:
                 list.append(question)
                 question = input("Please enter your 'to do' list: ")
            else:
                input("\n\nPress enter to exit")
                print(list)
                break
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-11-07
          • 2020-06-06
          • 2018-03-21
          • 2017-01-20
          • 1970-01-01
          • 2014-09-08
          • 2023-02-23
          相关资源
          最近更新 更多