在用python完成测验后,如何打印出用户答错的问题和用户答对的问题(分别)?

在用python完成测验后,如何打印出用户答错的问题和用户答对的问题(分别)?,python,function,printing,Python,Function,Printing,在用python完成测验后,如何打印出用户答错的问题和用户答对的问题(分别)?如果你想偷懒,可以将所有正确的问题数据保存在一个列表中,与不正确的问题数据相同,如我下面的示例中所示 我为你做了这么多的家庭作业,但我忽略了没有人支持填空。您可以简单地测试问题['answer']是字符串还是整数,然后基于此执行适当的操作。享受吧,我很无聊 import string print(("Welcome to the 'So You Think You Can Civics' quiz. This qu

在用python完成测验后,如何打印出用户答错的问题和用户答对的问题(分别)?

如果你想偷懒,可以将所有正确的问题数据保存在一个列表中,与不正确的问题数据相同,如我下面的示例中所示

我为你做了这么多的家庭作业,但我忽略了没有人支持填空。您可以简单地测试问题['answer']是字符串还是整数,然后基于此执行适当的操作。享受吧,我很无聊

import string


print(("Welcome to the 'So You Think You Can Civics' quiz. This quiz "
       "will test your knowledge on basic civics topics. Let's see "
       "if you were paying attention in Civics class!"))

questions = [
             {
              'question': 'Who is the current Prime Minister of Canada?',
              'options': ['Jean Chretien', 'Stephen Harper', 'Cam Guthrie',
                          'Dalton McGuinty', 'Steve Jobs'],
              'answer': 1,  # refers to the index of answer in options
             }
            ]

users_correct_questions = []
users_incorrect_questions = []
score = 0

for question in questions:
    print('\n' + question['question'])

    for i, option in enumerate(question['options']):
        print(string.ascii_lowercase[i] + ' ' + option)

    # selection must be between 0 and len(options) - 1
    viable_range = string.ascii_lowercase[:len(question['options'])]
    user_answer = 'Z'  # well, it'll never be this! :p

    while user_answer not in viable_range:
        user_answer = raw_input('Answer: ')#.lowercase()

    question['user_answer'] = user_answer

    if string.ascii_lowercase.index(user_answer) == question['answer']:
        score += 1
        users_correct_questions.append(question)
        print('Correct!')

    else:
        print('False!')
        users_incorrect_questions.append(question)

# let's print out each question which was incorrect, first!
if users_incorrect_questions:
    print("You got the following questions wrong...")

    for question in users_incorrect_questions:
        print("Question: " + question['question'])
        print("Your Answer: " + question['user_answer'])
        print("Correct Answer: " + question['options'][question['answer']])

# let's print out each question which was correct!
if users_correct_questions:
    print("\nYou got the following questions correct...\n")

    for question in users_correct_questions:
        print("Question: " + question['question'])
        print("Your Answer: " + question['user_answer'])

# Statistics
print("\nYour score is: %d out of %d" % (score, len(questions)))
percentage = (score / len(questions)) * 100
print("The percentage of questions answered correctly is %s%%" % percentage)
print('Thanks for completing the "So You Think You Can Civics" quiz!')

我认为这或多或少是可行的。当然,这里有一个稍微复杂一些的数据结构,也有很多代码需要避免重复

cont = ""

questions = [
    "What is the Zeroth Law of Thermodynamics?",
    "Who is the current Prime Minister of Canada?",
    "Which document outlines the specific rights guaranteed to all Canadian citizens?",
    "Which level of government is responsible for Tourism?",
    "Which of the following is not a Fundamental Freedom?",
    "(Fill in the blank) The three levels of government are Federal, Provincial and _______?",
    "(Fill in the blank) A two-house system of government is called ________?",
]

def get_answer(prompt):
    answer = input(prompt).lower()
    while not answer.isalpha():
        answer = input(prompt).lower()
    return answer

while cont != "n":
    score = 0
    qnum = 0
    right = []
    wrong = []
    print("Welcome to the 'So You Think You Can Civics' quiz.")
    print("This quiz will test your knowledge on basic civics topics.")
    print("Let's see if you were paying attention in Civics class!")

    qnum = qnum + 1
    for tries in range(2):
        print("\nQUESTION ", qnum, ":\n", questions[qnum])
        print(" a) Jean Chretien", "\n","b) Stephen Harper", "\n", "c) Cam Guthrie", "\n", "d) Dalton McGuinty", "\n", "e) Steve Jobs")
        answer = get_answer("Make your choice: ")
        if answer == "b":
            print("Correct!")
            score = score + 1
            right.append(qnum)
            break
        else:
            print("False!")
    else:
        wrong.append(qnum)
        print("Out of Chances!")

    qnum = qnum + 1
    for tries in range(2):
        print("\nQUESTION ", qnum, ":\n", questions[qnum])
        print(" a) The Universal Declaration of Human Rights", "\n", "b) The American Constitution", "\n", "c) The Canadian Charter of Rights and Freedoms", "\n", "d) The Ontario Human Rights Code", "\n", "e) The Convention on the Rights of the child")
        answer = get_answer("Make your choice: ")
        if answer == "c":
            print("Correct!")
            score = score + 1
            right.append(qnum)
            break
        else:
            print("False!")
    else:
        print("Out of Chances!")
        wrong.append(qnum)

    qnum = qnum + 1
    for tries in range(2):
        print("\nQUESTION ", qnum, ":\n", questions[qnum])
        print(" a) Municipal\n", "b) Federal\n", "c) Provincial\n", "d) All\n", "e) Legislative")
        answer = get_answer("Make your choice: ")
        if answer == "d":
            print("Correct!")
            score = score + 1
            right.append(qnum)
            break
        else:
            print("False!")
    else:
        print("Out of Chances!")
        wrong.append(qnum)

    qnum = qnum + 1
    for tries in range(2):
        print("\nQUESTION ", qnum, ":\n", questions[qnum])
        print(" a) Presumed innocent until proven guilty", "\n", "b) Conscience and Religion", "\n", "c) Opinion and Expression", "\n", "d) Assembly and Association", "\n", "e) Freedom of peaceful assembly")
        answer = get_answer("Make your choice: ")
        if answer == "a":
            print("Correct!")
            score = score + 1
            right.append(qnum)
            break
        else:
            print("False!")
    else:
        print("Out of Chances!")
        wrong.append(qnum)

    qnum = qnum + 1
    for tries in range(2):
        print("\nQUESTION ", qnum, ":\n", questions[qnum])
        answer = get_answer("Enter your answer: ")
        if answer == "municipal":
            print("Correct!")
            score = score + 1
            right.append(qnum)
            break
        else:
            print("False!")
    else:
        print("Out of Chances!")
        wrong.append(qnum)

    qnum = qnum + 1
    for tries in range(2):
        print("\nQUESTION ", qnum, ":\n", questions[qnum])
        answer = get_answer("Enter your answer: ")
        if answer == "bicameral":
            print("Correct!")
            score = score + 1
            right.append(qnum)
            break
        else:
            print("False!")
    else:
        print("Out of Chances!")
        wrong.append(qnum)

    print("Your score is: ", score,"/6")
    percent = (score/6)*100
    print(("Your percentage is:{0:2.0f} ".format(percent)),"%")

    if len(right) > 0:
        print("You got these questions right:")
        for r in range(len(right)):
            print(" ", right[r], ": ", questions[right[r]])

    if len(wrong) > 0:
        print("You got these questions wrong:")
        for w in range(len(wrong)):
            print(" ", wrong[w], ": ", questions[wrong[w]])

    cont = input("Continue (y) or (n):")

print("\nThanks for completing the 'So You Think You Can Civics' quiz!")
(请注意,在原始版本中,只要你在每次测验中至少答对一个问题,你最终会达到100%的正确率。通过这次修订,你不会获得这样的优势。)

样本运行:

$ python3 quiz.py
Welcome to the 'So You Think You Can Civics' quiz.
This quiz will test your knowledge on basic civics topics.
Let's see if you were paying attention in Civics class!

QUESTION  1 :
 Who is the current Prime Minister of Canada?
 a) Jean Chretien 
 b) Stephen Harper 
 c) Cam Guthrie 
 d) Dalton McGuinty 
 e) Steve Jobs
Make your choice: b
Correct!

QUESTION  2 :
 Which document outlines the specific rights guaranteed to all Canadian citizens?
 a) The Universal Declaration of Human Rights 
 b) The American Constitution 
 c) The Canadian Charter of Rights and Freedoms 
 d) The Ontario Human Rights Code 
 e) The Convention on the Rights of the child
Make your choice: b
False!

QUESTION  2 :
 Which document outlines the specific rights guaranteed to all Canadian citizens?
 a) The Universal Declaration of Human Rights 
 b) The American Constitution 
 c) The Canadian Charter of Rights and Freedoms 
 d) The Ontario Human Rights Code 
 e) The Convention on the Rights of the child
Make your choice: b
False!
Out of Chances!

QUESTION  3 :
 Which level of government is responsible for Tourism?
 a) Municipal
 b) Federal
 c) Provincial
 d) All
 e) Legislative
Make your choice: d
Correct!

QUESTION  4 :
 Which of the following is not a Fundamental Freedom?
 a) Presumed innocent until proven guilty 
 b) Conscience and Religion 
 c) Opinion and Expression 
 d) Assembly and Association 
 e) Freedom of peaceful assembly
Make your choice: a
Correct!

QUESTION  5 :
 (Fill in the blank) The three levels of government are Federal, Provincial and _______?
Enter your answer: munch
False!

QUESTION  5 :
 (Fill in the blank) The three levels of government are Federal, Provincial and _______?
Enter your answer: municipal
Correct!

QUESTION  6 :
 (Fill in the blank) A two-house system of government is called ________?
Enter your answer: bickering
False!

QUESTION  6 :
 (Fill in the blank) A two-house system of government is called ________?
Enter your answer: unicameral
False!
Out of Chances!
Your score is:  4 /6
Your percentage is:67  %
You got these questions right:
  1 :  Who is the current Prime Minister of Canada?
  3 :  Which level of government is responsible for Tourism?
  4 :  Which of the following is not a Fundamental Freedom?
  5 :  (Fill in the blank) The three levels of government are Federal, Provincial and _______?
You got these questions wrong:
  2 :  Which document outlines the specific rights guaranteed to all Canadian citizens?
  6 :  (Fill in the blank) A two-house system of government is called ________?
Continue (y) or (n):n

Thanks for completing the 'So You Think You Can Civics' quiz!
$
结构化重写 下面是代码的结构化版本;添加任意数量的额外问题、选择可用问题的子集、随机化问题的呈现顺序、只问在上一次迭代中出错的问题等应该非常简单

#!/usr/bin/env python3

questions = [

    {   'question': "Who is the current Prime Minister of Canada?",
        'correct': "b",
        'options': [
            "a) Jean Chretien",
            "b) Stephen Harper",
            "c) Cam Guthrie",
            "d) Dalton McGuinty",
            "e) Steve Jobs",
        ],
    },

    {   'question': "Which document outlines the specific rights guaranteed to all Canadian citizens?",
        'correct': "c",
        'options': [
            "a) The Universal Declaration of Human Rights",
            "b) The American Constitution",
            "c) The Canadian Charter of Rights and Freedoms",
            "d) The Ontario Human Rights Code",
            "e) The Convention on the Rights of the child",
        ],
    },

    {   'question': "Which level of government is responsible for Tourism?",
        'correct': "d",
        'options': [
            "a) Municipal",
            "b) Federal",
            "c) Provincial",
            "d) All",
            "e) Legislative",
        ],
    },

    {   'question': "Which of the following is not a Fundamental Freedom?",
        'correct': "a",
        'options': [
            "a) Presumed innocent until proven guilty",
            "b) Conscience and Religion",
            "c) Opinion and Expression",
            "d) Assembly and Association",
            "e) Freedom of peaceful assembly",
        ],
    },

    {   'question': "The three levels of government are Federal, Provincial and ________?",
        'correct': "municipal",
    },

    {   'question': "A two-house system of government is called ________?",
        'correct': "bicameral",
    },

]

right = []
wrong = []

def get_answer(prompt):
    answer = input(prompt).lower()
    while not answer.isalpha():
        answer = input(prompt).lower()
    return answer

def ask_question(qnum, qinfo):
    score = 0
    for tries in range(2):
        fitb = ""
        prompt = "Make your choice: "
        if not qinfo.get('options'):
            fitb = "(Fill in the blank)"
            prompt = "Enter your answer: "
        print("\nQUESTION", qnum, ":", fitb, qinfo['question'])
        if qinfo.get('options'):
            for opt in qinfo['options']:
                print(" ", opt)
        answer = get_answer(prompt)
        if answer == qinfo['correct']:
            print("Correct!")
            score = score + 1
            right.append(qnum)
            break
        else:
            print("False!")
    else:
        wrong.append(qnum)
        print("Out of Chances!")
    return score

def right_wrong(tag, qnos):
    if len(qnos) > 0:
        print("You got these questions", tag, ":")
        for n in range(len(qnos)):
            print(" ", qnos[n], ": ", questions[qnos[n]-1]['question'])

quiz = "'So You Think You Can Civics'"
cont = ""
while cont != "n":
    cont = "n"
    score = 0
    qnum = 0
    right = []
    wrong = []
    print("Welcome to the", quiz, "quiz.")
    print("This quiz will test your knowledge on basic civics topics.")
    print("Let's see if you were paying attention in civics class!")

    num_q = len(questions)
    for qnum in range(num_q):
        score += ask_question(qnum + 1, questions[qnum])

    print("")
    print("Your score is: ", score, "/", num_q)
    percent = (score / num_q) * 100
    print(("Your percentage is: {0:2.0f} ".format(percent)), "%")

    right_wrong("right", right)
    right_wrong("wrong", wrong)

    if score < num_q:
        cont = input("\nContinue (y) or (n): ")

print("\nThanks for completing the", quiz, "quiz!")
#/usr/bin/env蟒蛇3
问题=[
{‘问题’:“谁是加拿大现任总理?”,
“正确”:“b”,
“选项”:[
“a)让·克雷蒂安”,
“b)斯蒂芬·哈珀”,
“c)Cam Guthrie”,
“d)道尔顿·麦金蒂”,
“e)史蒂夫·乔布斯”,
],
},
{‘问题’:“哪份文件概述了保障所有加拿大公民的具体权利?”,
“正确”:“c”,
“选项”:[
“a)《世界人权宣言》”,
“b)美国宪法”,
“c)《加拿大权利和自由宪章》,
“d)《安大略人权法典》”,
“e)《儿童权利公约》”,
],
},
{‘问题’:“哪一级政府负责旅游业?”,
“正确”:“d”,
“选项”:[
“a)市政”,
“b)联邦”,
“c)省级”,
“d)所有”,
“e)立法”,
],
},
{‘问题’:“以下哪项不是基本自由?”,
“正确”:“a”,
“选项”:[
“a)在证明有罪之前推定无罪”,
“b)良心和宗教”,
“c)意见和表达”,
“d)集会和结社”,
“e)和平集会自由”,
],
},
{‘问题’:“三级政府分别是联邦、省和_________________,
“正确”:“市政”,
},
{‘问题’:“一个两院制的政府被称为uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu,
“正确”:“两院制”,
},
]
右=[]
错误=[]
def get_应答(提示):
回答=输入(提示).lower()
而不是回答。isalpha():
回答=输入(提示).lower()
回覆
def提问(qnum,qinfo):
分数=0
对于范围(2)内的尝试:
fitb=“”
prompt=“做出选择:”
如果不是qinfo.get('options'):
fitb=“(填写空格)”
prompt=“输入您的答案:”
打印(“\nQUESTION”,qnum,:”,fitb,qinfo['question'])
如果qinfo.get('options'):
对于选择加入qinfo[‘选项’]:
打印(“,opt)
答案=获取答案(提示)
如果答案==qinfo['correct']:
打印(“正确!”)
分数=分数+1
右。追加(qnum)
打破
其他:
打印(“假!”)
其他:
错误。追加(qnum)
打印(“机会不足!”)
回击得分
def对错(标签、qnos):
如果len(qnos)>0:
打印(“你有这些问题”,标签“:”)
对于范围内的n(len(qnos)):
打印(“,问题编号[n],”:“,问题编号[n]-1][“问题])
测验=“‘你认为你能做公民吗’”
cont=“”
继续“n”:
cont=“n”
分数=0
qnum=0
右=[]
错误=[]
打印(“欢迎参加”小测验“小测验”)
打印(“此测验将测试您对基本公民主题的知识。”)
打印(“让我们看看你在公民课上是否注意了!”)
num_q=len(问题)
对于范围内的qnum(num_q):
分数+=提问(qnum+1,问题[qnum])
打印(“”)
打印(“您的分数是:”,分数,“/”,num_q)
百分比=(分数/数量)*100
打印((“您的百分比为:{0:2.0f}.format(percent)),“%”)
对错(“对”,对)
对错(“错”,错)
如果分数

没有人声称这段代码是完美的,但它比以前的版本更有条理,更具python风格。

有人能帮帮我吗!这是一个相当讨厌的代码块。你确定代码中没有隐藏的函数吗?你们需要一个问题文本列表。无论如何,您要保留一份正确回答的问题编号记录(此类编号的列表)和另一份错误回答的编号列表,然后在最后您可以从问题列表中打印每个列表中引用的问题。您还可以识别任何未尝试的问题。您不能将值存储在字典中吗?Like answers={'name':'john','true_answers':['q1','q2'],'false_answers':[q4,q5]}非常感谢@JonathanLeffler,你有什么办法可以告诉我你的意思吗?:)