2012-08-07 87 views
0

對python /編程來說很新,這是我最大的項目。(Python)For循環語法 - 只執行一個項目?

我在寫一個程序,可以爲你做SUVAT方程。 (SUVAT公式用於查找排量,開始/結束的速度,加速度,並通過與等速對象旅行時,你可以打電話給他們不同的東西。)

我做了這個名單:

variables = ["Displacement", "Start Velocity", "End Velocity", "Acceleration", "Time"] 

這是在下面的,而使用/ for循環:

a = 0 
while a==0: 
    for variable in variables: 

    # choice1 is what the user is looking to calculate 
    choice1 = raw_input("Welcome to Mattin's SVUVAT Simulator! Choose the value you are trying to find. You can pick from " + str(variables)) 

    # will execute the following code when the for loop reaches an item that matches the raw_input 
    if choice1 == variable: 
     print "You chave chosen", choice1 
     variables.remove(variable) #Removes the chosen variable from the list, so the new list can be used later on 
     a = 1 # Ends the for loop by making the while loop false 

    # This part is so that the error message will not show when the raw_input does not match with the 4 items in the list the user has not chosen 
    else: 
     if choice1 == "Displacement": 
      pass 
     elif choice1 == "Start Velocity": 
      pass 
     elif choice1 == "End Velocity": 
      pass 
     elif choice1 == "Acceleration": 
      pass 

     # This error message will show if the input did not match any item in the list 
     else: 
      print "Sorry, I didn't understand that, try again. Make sure your spelling is correct (Case Sensitive), and that you did not inlcude the quotation marks." 

希望我已經寫在代碼中的註釋應該解釋我的意圖,如果不是,隨便問什麼。

的問題是,當我運行的代碼,輸入選擇1,for循環激活代碼的最後一行:

else: 
    print "Sorry, I didn't understand that, try again. Make sure your spelling is correct (Case Sensitive), and that you did not inlcude the quotation marks." 

,然後提示我再次進入輸入,並會做,因爲很多次,因爲它需要到我正在打字的列表上的項目。

但是,我特別編碼,如果我輸入的內容與列表上的項目不匹配for循環當前正在檢查,但確實與列表中的其他項目匹配,那麼它應該傳遞並循環檢查下一個項目。

我可能在做一些愚蠢的事情,但我沒有看到它,所以請幫我弄清楚我必須做些什麼來獲得我想要的結果?我認爲這是我錯了的語法,所以這就是爲什麼這是標題。

感謝您的任何幫助,我欣賞它。

+1

修復您的縮進 – 2012-08-07 10:36:46

回答

2

除了在你的粘貼代碼的縮進問題,我將它改寫爲這樣的:

while True: 
    choice = raw_input('...') 

    if choice in variables: 
     print "You chave chosen", choice 

     # Remove the chosen member from the list 
     variables = [v for v in variables if v != choice] 

     # Break out of loop 
     break 

    # Print error messages etc. 

還記得字符串比較是區分大小寫的。 I。'Displacement' != 'displacement'

+0

抱歉,縮進的事情,這是一個粘貼錯誤,不是在程序上,但我已經修復它。 你說過的話會起作用我想,但我該如何讓它從列表中刪除所選的項目? – 2012-08-07 11:04:21

+0

@Ricochet_Bunny使用一種可能的解決方案更新答案以刪除所選項目。 – 2012-08-07 11:07:06

+0

謝謝,這真的很棒,它的工作!如果你有時間,你會介意解釋你添加的行嗎?我還沒有見過像以前那樣使用過的東西。 – 2012-08-07 11:11:30