简单测试 - 如何链接变量

2024-04-25 01:07:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在想怎样把正确的答案和正确的问题搭配起来。现在,如果用户的答案等于任何一个答案,则返回correct。请帮忙。你知道吗

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))

Tags: and答案answerinputreturnistypeeasy
2条回答

我的方法是:创建2个变量,x和y。如果用户选择“Easy”,它将x设置为1,“Medium”将其设置为2,依此类推。然后你问他一个答案。简单问题的答案,如果正确的话,将y设置为1,在中等偏上设置为2,依此类推。如果x==y,你就要检查一下。如果是的,那么他对这个问题的回答是正确的。你知道吗

您需要跟踪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}

您创建了一个字典(或者在Python中称为dict)。见examples。基本上,您可以按第一个术语(问题)进行查找,它将返回第二个术语(答案)。你知道吗

相关问题 更多 >