2016-10-03 76 views
-1

我一直在試圖弄清楚如何將正確的答案與正確的問題進行匹配。現在,如果用戶的答案等於任何答案,則返回正確。請幫忙。簡單測驗 - 如何鏈接變量?

easy_question = "The capitol of West Virginia is __1__" 
medium_question = "The device amplifies a signal is an __2__" 
hard_question = "A program takes in __3__ and produces output." 

easy_answer = "Charleston" 
medium_answer = "amplifier" 
hard_answer = "input" 

questions_and_answers = {easy_question: easy_answer, 
        medium_question: medium_answer, 
        hard_question: hard_answer} 
#print(easy_answer in [easy_question, easy_answer]) 
#print(questions_and_answers[0][1]) 

print('This is a quiz') 
ready = input("Are you ready? Type Yes.") 
while ready != "Yes": 
    ready = input("Type Yes.") 
user_input = input("Choose a difficulty: Easy, Medium, or Hard") 

def choose_difficulty(user_input): 
    if user_input == "Easy": 
     return easy_question 
    elif user_input == "Medium": 
     return medium_question 
    elif user_input == "Hard": 
     return hard_question 
    else: 
     print("Incorrect") 
     user_input = input("Type Easy, Medium, or Hard") 
print(choose_difficulty(user_input)) 


answer = input("What is your answer?") 
def check_answer(answer): 
    if answer == easy_answer: 
     return "Correct" 
    elif answer == medium_answer: 
     return "Correct" 
    elif answer == hard_answer: 
     return "Correct" 
print(check_answer(answer)) 
+0

你還沒有嘗試在'check_answer'中返回除''Correct''之外的任何東西。 – TigerhawkT3

+0

因爲'if/elif'將會繼續檢查條件,直到事情成立,然後你將遇到'return'條件。在'check_answer'中,你只要繼續下去,直到找到正確的東西。 – roganjosh

回答

1

你會希望保持question的軌跡:

question = choose_difficulty(user_input) 
print(question) 

answer = input("What is your answer?") 
def check_answer(question, answer): 
    if questions_and_answers[question] == answer: 
     return "Correct" 
    return "Incorrect" 
print(check_answer(question, answer)) 

還有很多更有趣的東西,你可以做,但是這是一個應該解決您的問題小例子!

編輯:

當你做

questions_and_answers = {easy_question: easy_answer, 
       medium_question: medium_answer, 
       hard_question: hard_answer} 

您創建了一個字典(或dict因爲它在Python的已知)。見examples。基本上,你可以在第一學期(問題)進行查找,並返回第二學期(答案)。

+0

非常感謝!那麼,「如果questions_and_answers [問題] ==回答」是什麼呢? – MrWizard

-1

我會這樣做的方式:創建2個變量,x和y。如果用戶選擇「Easy」,它將x設置爲1,「Medium」將其設置爲2等等。然後你問他一個答案。對於簡單問題的答案,如果正確,則將y設置爲1,將介質設置爲2,等等。然後你有一個檢查,如果x == y。如果是,那麼他已經正確回答了這個問題。

+0

這不起作用,並沒有解決原始代碼的限制。 OP是按照正確答案的正確答案在字典中進行映射的正確方式,並且已經爲您提供了比您提供的問題更全面的答案 – roganjosh