2014-01-28 39 views
1

我只是盯着Python,我認爲這將是一個有趣的小測驗。我遇到的問題是,當考慮到國會大寫字母&常見拼寫錯誤時,有很多可能的答案。我想解釋這些,但沒有一堆'elif'函數。有沒有辦法將所有可能的答案都放到一行上?類似於||的東西在C. 代碼示例:多個可能的輸入

y = input("Where was the 2004 Olympics held? ") 
if y == "Athens": 
    print ("Correct!") 
    score = score + 1 

但允許'athens''Greece'作爲回答

回答

4

你想要的是:

answer = input("Where was the 2004 Olympics held? ") 
if answer.lower() in ("athens", "greece"): 
    print ("Correct!") 
    score = score+1 

我也降低了答案,這樣的情況不物!

N.B:建立一個測驗,在這裏就是我會做它:

qas = { 
    'Where was the 2004 Olympics held?': ['athens', 'greece'], 
    'What is the answer of the question about life, the universe and everything?': ['42', 'forty-two'] 
    … 
} 

for q, a in qas: 
    ans = input(q) 
    if ans.lower() in a: 
     print("Correct!") 
     score += 1 
+0

謝謝。這一切都縮進了,但複製粘貼似乎弄亂了它。 – Tommig1995

1

是啊!

只要做到:

if y in ["athens", "blah", "other",...]: 
    print ("Correct!") 
    score += 1 
1
y = input("Where was the 2004 Olympics held? ") 
if y in ["Athens","Greece"]: 
    print ("Correct!") 
    score = score+1 
3
if y.lower() in ["athens", "greece"]: 
    print("Correct!")