使用Python的多项选择测验

Cas*_*ian 0 python

我正在编写一个程序,该程序管理有关全球变暖的五个问题的多项选择测验,并计算正确答案的数量。我首先创建了词典字典,例如:

questions = \
{
    "What is the global warming controversy about?": {
        "A": "the public debate over whether global warming is occuring",
        "B": "how much global warming has occured in modern times",
        "C": "what global warming has caused",
        "D": "all of the above"
    },
    "What movie was used to publicize the controversial issue of global warming?": {
        "A": "the bitter truth",
        "B": "destruction of mankind",
        "C": "the inconvenient truth",
        "D": "the depletion"
    },
    "In what year did former Vice President Al Gore and a U.N. network of scientists share the Nobel Peace Prize?": {
        "A": "1996",
        "B": "1998",
        "C": "2003",
        "D": "2007"
    },
    "Many European countries took action to reduce greenhouse gas before what year?": {
        "A": "1985",
        "B": "1990",
        "C": "1759",
        "D": "2000"
    },
    "Who first proposed the theory that increases in greenhouse gas would lead to an increase in temperature?": {
        "A": "Svante Arrhenius",
        "B": "Niccolo Machiavelli",
        "C": "Jared Bayless",
        "D": "Jacob Thornton"
    }
}
Run Code Online (Sandbox Code Playgroud)

那么逻辑如下:

print("\nGlobal Warming Facts Quiz")
prompt = ">>> "
correct_options = ['D', 'C', 'D', 'B', 'A']
score_count = 0

for question, options in questions.items():
    print("\n", question, "\n")
    for option, answer in options.items():
        print(option, ":", answer)
    print("\nWhat's your answer?")
    choice = str(input(prompt))
    for correct_option in correct_options:
        if choice.upper() == correct_option:
            score_count += 1
print(score_count)
Run Code Online (Sandbox Code Playgroud)

问题是,如果我输入所有正确的选项,我得到7而不是5。我尝试在if语句下推送最后一个语句(print(score_count))以监视分数计数,我发现有些问题实际上加了1而不是2就一次。

pka*_*zak 5

这是因为,对于每个问题,您都在遍历所有问题的所有正确选项,而不是检查所提供的选项是否仅等于当前问题的正确选项。换句话说,这部分是错误的:

for correct_option in correct_options:
        if choice.upper() == correct_option:
            score_count = score_count + 1
Run Code Online (Sandbox Code Playgroud)

尝试以下方法:

print("\nGlobal Warming Facts Quiz")
prompt = ">>> "
correct_options = ['D', 'C', 'D', 'B', 'A']
score_count = 0

for correct_option, (question, options) in zip(correct_options, questions.items()):
    print("\n", question, "\n")
    for option, answer in options.items():
        print(option, ":", answer)
    print("\nWhat's your answer?")
    choice = str(input(prompt))
    if choice.upper() == correct_option:
        score_count = score_count + 1
print(score_count)
Run Code Online (Sandbox Code Playgroud)