【问题标题】:Multiple-choice quiz using Python使用 Python 进行多项选择测验
【发布时间】:2017-08-14 01:02:46
【问题描述】:

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

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"
    }
}

那么逻辑如下:

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)

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

【问题讨论】:

    标签: python


    【解决方案1】:

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

    for correct_option in correct_options:
            if choice.upper() == correct_option:
                score_count = score_count + 1
    

    试试这个:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-09
      • 2017-06-09
      • 1970-01-01
      相关资源
      最近更新 更多