2016-11-12 29 views
0

我需要在程序中創建'while'循環,但無法正確完成。下面是我到目前爲止有:如何在Python中爲兩個答案寫'不等於'?

restart ="y" 
while restart == "y": 
    sentence = input("What is your sentence?: ") 
    sentence_split = sentence.split() 
    sentence2 = [0] 
    print(sentence) 
    for count, i in enumerate(sentence_split): 
     if sentence_split.count(i) < 2: 
      sentence2.append(max(sentence2) + 1) 
     else: 
      sentence2.append(sentence_split.index(i) +1) 
    sentence2.remove(0) 
    print(sentence2) 
    outfile = open("testfile.py", "wt") 
    outfile.write(sentence) 
    outfile.close() 
    print (outfile) 
    restart = input("would you like restart the programme y/n?") 
    if restart == "n": 
     print ("programme terminated") 
    else: 
     print("you were asked y or n") 

當進入「N」是那麼迴路工作正常,它打印「節目結束」,但「Y」被輸入時,它會重新啓動該程序,但也還是打印「你被問y或n「。

回答

2

這是因爲如果restart保存與「n」不同的任何東西,程序將會遵循else。 (y或任何其他值)。如果按'y',則會按照else聲明進行操作,然後此時的條件也將評估爲true。您可以使用elif restart != 'y'作爲發佈print語句的快速解決方案。然後,您可以將restart設置爲y,以便重複循環,或者爲循環完全使用不同的變量。

-1
if restart == "n": 
    print ("programme terminated") 
else if restart == "y": 
    print("restarting") 
else: 
    print("you were asked y or n") 

也許這是你的意圖?

+0

不,這不是。他有一段時間來重新啓動他的程序。他不只是想打印''重新啓動''。 –

+0

@leaf好吧,這不會打印出「你被問及或你」,這是我認爲他想要的,他究竟想要什麼? –

+0

也許我誤解了你。這是否意味着工作代碼?如果不是,我表示歉意,可能會意外地得出一些錯誤的結論。 –

0

使用while: truebreak來控制y/n的問題,並記住使用lower()只能得到小寫字符。

restart = 'y' 
while (True): 
    # other code goes here 
    restart = raw_input("would you like restart the programme y/n?").lower() 
    if (restart == 'n'): 
     print ("programme terminated") 
     break 
    elif (restart == 'y'): 
     pass 
    else: 
     print "Please enter y or n" 
0

這是因爲您的if/else語句的結構。當您在if語句中輸入yn時失敗。這意味着您的else聲明立即執行。但是在執行else語句之後,控制流將循環到while循環的下一個迭代中,並且程序仍會重新啓動。

你最有可能想要的是添加你else語句下break語句,因此控制該流不循環到while循環的下一次迭代,但離開它:

else: 
    print("you were asked y or n") 
    break # <---------- add a break statement under your else 
相關問題