2017-01-11 36 views
-3

這是我所做的代碼,它只是整個更大的事情的一小部分。我如何把它放在一個while循環中,這樣它會重複"Invalid answer, try again."直到給出正確的答案?我已經嘗試了很多小時來看while循環,但不能做到這一點。如果你確實會運行代碼它顯然將拿出錯誤,因爲你沒有路徑等重複,直到給出正確的答案

下面是代碼:

shortestpath = raw_input("Give the shortest path? (Y/N)") 
if shortestpath == "Y" or shortestpath == "y": 
    answer = min(path1, path2, path3, path4, path5, path6, path7, path8, path9) 
    print "The shortest path is: " 
    print answer 
    if answer == path1: 
     print "a,f,e" 
    elif answer == path2: 
     print "a,c,f,e" 
    elif answer == path3: 
     print "a,f,c,d,e" 
    elif answer == path4: 
     print "a,f,c,b,d,e" 
    elif answer == path5: 
     print "a,c,d,e" 
    elif answer == path6: 
     print "a,c,b,d,e" 
    elif answer == path7: 
     print "a,b,c,f,e" 
    elif answer == path8: 
     print "a,b,c,d,e" 
    elif answer == path9: 
     print "a,b,d,e" 
elif shortestpath == "N" or shortestpath == "n": 
    print "End of program." 
else: 
    print "Invalid answer, try again." 
+0

使用'break'退出循環離開'而TRUE'當答案是正確的。 – furas

+0

順便說一句:你可以用'for-loop'來檢查答案,使用list'path'和'path [1]','path [2]'等。並且'answer = min(path)' – furas

+0

順便說一句:如果shortestpath.lower()==「y」:'或'如果最短路徑在(「Y」,「y」)中:' – furas

回答

0

包裝你的代碼在while循環。一旦你的代碼達到一個正確的答案,你可以用break

while True: 
    shortestpath = raw_input("Give the shortest path? (Y/N)") 
    if shortestpath == "Y" or shortestpath == "y": 
     answer = min(path1, path2, path3, path4, path5, path6, path7, path8, path9) 
     print "The shortest path is: " 
     print answer 
     if answer == path1: 
      print "a,f,e" 
     elif answer == path2: 
      print "a,c,f,e" 
     elif answer == path3: 
      print "a,f,c,d,e" 
     elif answer == path4: 
      print "a,f,c,b,d,e" 
     elif answer == path5: 
      print "a,c,d,e" 
     elif answer == path6: 
      print "a,c,b,d,e" 
     elif answer == path7: 
      print "a,b,c,f,e" 
     elif answer == path8: 
      print "a,b,c,d,e" 
     elif answer == path9: 
      print "a,b,d,e" 
     break 
    elif shortestpath == "N" or shortestpath == "n": 
     print "End of program." 
     break 
    else: 
     print "Invalid answer, try again." 
+0

你只需要一個'如果最短路徑=='Y'''和'elif shortestpath =='N''另一個'break'裏面' – furas

+0

@furas你是對的。 – Jfach

0
def get_answer(prompt,options): 
    while True: 
     result = raw_input(prompt) 
     if result in options: return result 
     print "Got unexpected input ... please try again" 

selected_option = get_answer("Would you like to _____?",options=["y","Y","n","N"]) 
相關問題