在python中完成测验后,如何打印出用户出错的问题和用户正确的问题(单独)?

时间:2015-05-23 05:12:26

标签: python function printing

在python中完成测验后,如何打印出用户出错的问题和用户正确的问题(单独)?

2 个答案:

答案 0 :(得分:1)

如果您想要懒惰,可以将所有正确的问题数据保存在列表中,与错误的一样,如下面的示例所示......

我做了这么多的功课,但我忽略了那里没有支持填空。您可以简单地测试问题[' 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!')

答案 1 :(得分:0)

我认为这或多或少都有效。这肯定是一个稍微复杂的数据结构,而且很少有代码可以摆脱这种材料的重复。

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%正确。您不会通过此修订获得此优惠。)< / p>

示例运行:

$ 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!
$

结构化重写

这是代码的结构化版本;添加任意数量的额外问题,选择可用问题的子集,随机化问题的呈现顺序,只提出他们在前一次迭代中出错的问题,等等,应该非常简单。 / p>

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

没有声称这段代码是完美的,但它比以前的版本更有条理和Pythonic。