【问题标题】:Does raw_input() stop an infinite while loop?raw_input() 是否会停止无限循环?
【发布时间】:2015-07-12 07:20:21
【问题描述】:

下面有一段包含while循环的小代码。

question = raw_input("How are you? > ")
state = True
number = 0
print "Hello"

while True:
    if question == "good":
        print "Ok. Your mood is good."
        state = False
        question_2 = raw_input("How are you 2? > ")
    elif question == "normal":
        print "Ok. Your mood is normal."
    elif question == "bad":
        print "It's bad. Do an interesting activity, return and say again what your mood is."
    else:
        print "Nothing"

如果我输入 "normal",程序会打印 Ok。你的心情很正常。无数次。

但如果我输入 "good",程序会打印 Ok。你的心情正常。并打印question_2的内容。

为什么question_2 = raw_input("How are you 2? > ") 中的问题没有重复无数次?

判断raw_input() 停止任何无限while循环是否合理?

【问题讨论】:

  • 听起来很奇怪,你确定是while True: 而不是while state:
  • 是的。我还没有结束这段代码,状态是为了其他步骤。

标签: python while-loop infinite-loop


【解决方案1】:

没有。这不是停止循环;它正在积极阻止输入。一旦收到输入,它将不再被阻止(这就是为什么您会从其他选择中获得无限文本);这些分支中没有阻塞 I/O。

您没有从选项 1 中获得大量文本输出的原因是它的评估方式。在循环内部,question 永远不会改变,所以它总是会评估为 "good" 并且会不断地问你第二个问题1

1:如果确实是while True,这是如果是while state,它将停止迭代,因为state 在后续运行中是False

【讨论】:

  • 非常感谢!对不起,我在文本中的错误,英语不是我的母语。
【解决方案2】:

一旦您回答“好”,第二个 raw_input 返回的值将存储在变量 question_2 而不是问题中。所以变量 question 永远不会再改变,但会保持“好”。所以你会继续点击第二个raw_input,不管你回答什么。它不会停止你的循环,而是暂停它直到你回答。我认为你也应该好好看看 Alfasin 的评论......

【讨论】:

    【解决方案3】:

    您可以通过使用break 输出的elseelif 来停止无限循环。希望有帮助! :D

    例子:

    while True:
        if things:
            #stuff
        elif other_things:
            #other stuff
        #maybe now you want to end the loop
        else:
            break 
    

    【讨论】:

      【解决方案4】:

      raw_input() 不会中断循环。它只是等待输入。并且由于您的 question 不会被第二个 raw_input() 覆盖,因此您的 if 块将始终以 good 的情况结束。

      另一种方法:

      answer = None
      
      while answer != '':
          answer = raw_input("How are you? (enter to quit)> ")
          if answer == "good":
              print( "Ok. Your mood is good.")
          elif answer == "normal":
              print( "Ok. Your mood is normal.")
              # break ?
          elif answer == "bad":
              print( "It's bad. Do an interesting activity, return and say again what your mood is.")
              # break ?
          else:
              print( "Nothing")
              # break ?
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-26
        • 2021-10-21
        • 2015-02-07
        • 1970-01-01
        • 1970-01-01
        • 2013-07-27
        • 2017-11-16
        相关资源
        最近更新 更多