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

2024-04-19 00:51:19 发布

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

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


Tags: 用户
2条回答

我想这或多或少管用。而且肯定有一个稍微复杂一点的数据结构和大量的代码哭着逃离重复在这个材料。你知道吗

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

没有人声称这段代码是完美的,但它比上一个版本更有组织性和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!')

相关问题 更多 >