我正在编写一个管理五个问题的程序 - 关于全球变暖的选择测验并计算数字 正确的答案。 我首先创建了一个字典词典,如:
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))为了监控分数,我发现有些问题实际上增加了两次而不是一次。
答案 0 :(得分:5)
这是因为对于每个问题,您正在迭代所有问题的所有正确选项,而不是检查提供的选项是否等于当前问题的正确选项。换句话说,这部分是错误的:
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)