2015-10-05 79 views
0

我在我的大學的入門csci課程中編寫的程序是對用戶症狀的小型診斷。除了一件事情之外,所有事情都應該如此:如果使程序運行的初始條件(無論用戶是否發燒)爲「否」或「n」,則程序將不會重新啓動重新定義使while循環運行的變量。Python - 忽略重新啓動while循環

取而代之的是,程序在接收到用戶關於是否重新啓動程序的輸入而不是重新開始while循環之後繼續。這會產生問題,因爲程序進入下一行代碼並達到未定義的變量。

這隻發生在第一個if,else語句中,並且在隨後的語句中沒有問題。它只發生第一次 while循環變量被重新定義。在其他任何時候,它都可以工作。

即使第一個「else」重新定義「完成」,應該使while循環重新啓動,它不會重新啓動。但是,對於用戶重新定義「完成」的每個後續時間,則重新啓動的while循環。奇。縮進錯誤?我不知道。雙星號是while循環需要重新啓動的地方,但不是。無論用戶輸入如何,它都會繼續嘗試繼續,並且出現錯誤提示「咳嗽」未定義,表示while循環未重新啓動。

這裏是我的代碼:

#Proj2.py 

finished = "y" 
while finished == "y": 

    print() 
    print("Fever Diagnostic Tool") 
    print("---------------------") 
    print() 
    print("Please note that this program performs no true diagnostic \nactivity. No decisions should be made based upon the tool's \nanalysis. If users have a fever, they should contact their \ndoctor.") 
    print() 
    print() 

    FirstDiagnosis = str(input("Do you have a fever (y/n): ")).lower() 
    print(FirstDiagnosis) 
    if FirstDiagnosis == "y": 
     cough = "" 
     cough = str(input("Are you coughing (y/n): ")).lower() 
     print(cough) 
    else: 
     print() 
     print("Symptoms") 
     print("* None") 
     print() 
     print("Diagnosis") 
     print(" Insufficient information to list possibilites.") 
     print() 
     print() 
     **finished = str(input("Would you like another set of symptoms? ")).lower()** 
     print() 
    if cough == "y": 
     ShortOfBreath = "" 
     ShortOfBreath = str(input("Are you short of breath or wheezing or coughing up phlem (y/n): ")).lower() 
     print(ShortOfBreath) 
+0

我喜歡你的節目覺得需要添加免責聲明;-) – donkopotamus

+1

語義,我會說'同時完成!=「y」' – Pynchia

+1

請在開始時編輯您的代碼..完成時我假設'finished =「y」==「y」:代碼的一部分,需要更多縮進然後 – Pynchia

回答

1

這不是如何while循環工作。一旦身體任何部位的狀況變得虛假,他們就不會戒菸;該條件僅在塊的結尾處被評估,此時它決定是否再次循環(如果條件仍然成立)或中斷(如果不成立)。

在這種情況下,最容易做的事情就是使用break聲明明確:

finished = input("Would you like another set of symptoms? ").lower() 
if finished == 'y': 
    break 
+1

輸入不是「y」時不應該中斷嗎? – tdelaney