首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >raw_input()会停止无限时间循环吗?

raw_input()会停止无限时间循环吗?
EN

Stack Overflow用户
提问于 2015-07-12 07:20:21
回答 3查看 943关注 0票数 0

下面有一个包含while循环的小代码.

代码语言:javascript
复制
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。你的心情很正常。无数次。

但是如果我输入“很好”,程序就会打印Ok。你的心情很正常。并打印question_2的内容。

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

得出raw_input()停止无限时间循环的结论是否合理?

EN

回答 3

Stack Overflow用户

发布于 2015-07-12 07:25:45

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

票数 0
EN

Stack Overflow用户

发布于 2015-12-18 21:47:14

您可以通过使用elseelif输出break来停止无限循环。希望这能帮上忙!

示例:

代码语言:javascript
复制
while True:
    if things:
        #stuff
    elif other_things:
        #other stuff
    #maybe now you want to end the loop
    else:
        break 
票数 0
EN

Stack Overflow用户

发布于 2015-07-12 07:24:18

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

另一种方法:

代码语言:javascript
复制
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 ?
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31365392

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档