2013-11-09 37 views
2

開始學習Python,所以如果這個問題看起來非常明顯,請耐心等待。我正在嘗試創建一個高分程序,在該程序中,該程序將使用列表方法創建並維護電腦遊戲的最佳用戶列表。然而,發生的事情是,雖然我根據用戶輸入有適當的代碼,但while循環會繼續執行並忽略用戶輸入。請看下面的代碼,會很喜歡我做錯的答案。提前致謝。如何關閉while循環,然後執行另一個代碼塊?雖然循環總是重複

scores =[] 
choice = None 

while choice != "0": 
    print """"High Scores Keeper 
    0 - Exit 
    1 -Show Scores 
    2 - Add A score 
    3- Delete a score. 
    4- Sort Scores""" 
    choice = raw_input("Choice:") 
    print 


    if choice == "0": 
     print "Good Bye" 

    elif choice == "1": 
     print "High Scores" 
     for score in scores: 
      print score 

    elif choice == "2": 
     score = int(raw_input("What score did you get?: ")) 
     scores.append(score) 

當我執行的循環,我選擇1爲例,而非打印的高分,循環只是去上再次和它相同的兩個。請幫忙。

回答

1

你編碼你的循環,這樣它會繼續進行,而choice != "0",只會從choice == "0"跳出循環。如果你想與"1"打出來的循環,你需要的是對應於一個循環條件:

while choice != "0" and chioce != "1" and choice != "2" and ... 

或者你可以在一個更簡潔的方式把它寫:

while 0 <= int(choice) and int(choice) <= 4: 

while choice not in ["0", "1", "2", "3", "4", "5"]: 

#or something like that. 
+0

我不確定我是否遵循,例如,假設用戶輸入「1」,然後打印的是高分,然後將最早的分數放入該程序(假設有人已經放入分數),會然後再打印High Scores Keeper字符串? – TKA

1
scores =[] 
choice = None 

while choice != "0": 
    print """High Scores Keeper 
    0- Exit 
    1- Show Scores 
    2- Add A score 
    3- Delete a score. 
    4- Sort Scores""" 
    choice = raw_input("Choice:") 
    if choice == "0": 
     print "Good Bye" 
    elif choice == "1": 
     print "High Scores" 
     for score in scores: 
      print score 
    elif choice == "2": 
     score = int(raw_input("What score did you get?: ")) 
     scores.append(score) 
+0

謝謝阿拉丁,我看到縮進是一個強大的東西在蟒蛇:) – TKA

+0

縮進是在python中的每一件事;) – Aladdin