2015-05-28 37 views
1
while True: 

print "Please choose from one of the five following options:" 

print " 1. 10^1\n 2. 10^2\n 3. 10^3\n 4. 10^4\n 5. 10^5\n" 
    choice = raw_input() 

    if choice == 1: 
     print "1" 
    elif choice == 2: 
     print "2" 
    elif choice == 3: 
     print "3" 
    elif choice == 4: 
     print "4" 
    elif choice == 5: 
     print "5" 

    while choice not in [1,2,3,4,5]: 
     print "Not a valid choice!\n" 
     break 

我應該使用什麼語法?我一直沒有得到一個有效的選擇。它像Python一樣將每個選擇甚至1,2,3,4,5放置在該列表之外的點列表中。Python Choice不在列表中

+0

你的while循環是不必要的。把它放在if語句中的else子句中。 –

回答

3

您需要的raw_input轉換爲int:

choice = int(raw_input()) 

choiceraw_input類型將是一個str這就是爲什麼沒有比賽,所以你需要更改所有if比較與字符或轉換選擇一個int

編輯

根據評論意見,最好是將比較結果與單個字符串進行比較,因爲無論如何,這都是您的意圖;其次,它可以防止無效轉換,例如,如果您輸入的輸入值不能被強制轉換爲int那麼這將拋出一個異常,所以我修改代碼以這樣的:

choice = raw_input() 

if choice == "1": 
    print "1" 
elif choice == "2": 
    print "2" 
elif choice == "3": 
    print "3" 
elif choice == "4": 
    print "4" 
elif choice == "5": 
    print "5" 

while choice not in ["1","2","3","4","5"]: 
    print "Not a valid choice!\n" 
    break 
+0

謝謝@EdChum!仍在學習Python基礎知識。我很感激! – seeaemearohin

+1

在這種情況下,更好的解決方案可能是針對字符串進行測試,因爲否則如果用戶輸入非整數,程序將會禁止。當然,你可能會陷入困境,但更容易僅僅用字符串來測試! – kindall

+0

@kindall是我同意這是爲什麼我建議修改'if'條件檢查 – EdChum

1

我會用字典,檢查鍵/選擇是在字典,如果是打印選擇和其他打印"Not a valid choice!\n"消息:

# map choice to whatever you want to print 

d = {"1": "1", "2": "2", "3": "3", "4": "4", "5": "5"} 
while True: 
    choice = raw_input("Please choose from one of the five following options:\n" 
         "1. 10^1\n 2. 10^2\n 3. 10^3\n 4. 10^4\n 5. 10^5\n") 
    # if the key is in the dict, the choice is valid 
    # so print the choice value and break. 
    if choice in d: 
     print(d[choice]) 
     break 
    # if we get here choice was invalid 
    print "Not a valid choice!\n" 

將不會有將選項轉換爲int,將其保留爲字符串,並使用字符串作爲關鍵字在dict上執行查找。您可以將每個選擇的值存儲爲字典中的值。

-1
while True: 

    print "Please choose from one of the five following options:" 

    print " 1. 10^1\n 2. 10^2\n 3. 10^3\n 4. 10^4\n 5. 10^5\n" 
choice = raw_input() 

if choice == 1: 
    print "1" 
elif choice == 2: 
    print "2" 
elif choice == 3: 
    print "3" 
elif choice == 4: 
    print "4" 
elif choice == 5: 
    print "5" 

else: 
    print "Not a valid choice!\n" 

這應該是最簡單的解決