2015-07-12 163 views
0

下面有一個包含while循環的小代碼。raw_input()停止無限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" 

如果我在「正常」,該程序將打印好的類型。你的心情很正常。無數次。

但是,如果我輸入「好」,程序打印好的。你的心情很正常。並打印question_2的內容。

爲什麼question_2 = raw_input("How are you 2? > ")中的問題無法重複無數次?

是否有理由得出結論raw_input()停止任何無限的while循環?

+1

這聽起來很奇怪,你確定它是'while true:'而不是'while state:'? – alfasin

+0

是的。我還沒有結束這個代碼,狀態是爲了其他步驟。 –

回答

2

號這不是停止循環;它主動阻止輸入。一旦收到輸入,它就不會被阻止(這就是爲什麼你從其他選擇無限的文本);這些分支中沒有阻塞I/O。

你沒有從選項1得到大量文本輸出的原因是由於它被評估的方式。在循環內,question永不改變,所以它的總是要評估到"good",並會不斷問你第二個問題。

1:如果確實是while True;如果它是while state,則由於在隨後的運行中stateFalse而停止迭代。

+0

非常感謝!對不起,我的錯誤在文中,英文不是我的母語。 –

-1

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 ? 
0

一旦你回答「好,第二個raw_input返回的值將被存儲在變量question_2中而不是問題中,所以變量問題不會再發生變化,但會保持」良好「狀態。第二次raw_input,不管你回答什麼,它不會停止你的循環,而是暫停它,直到你回答。我認爲你也應該仔細看看Alfasin的評論...

0

您可以通過使用break輸出elseelif來停止無限循環。希望有幫助!:D

示例:

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