如何在python中创建一个包含多个主题的简单测验?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26792705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:01:32  来源:igfitidea点击:

How to create a simple quiz in python with multiple topics?

python

提问by Carar

I'm new to python and don't know much but think I could make quizzes pretty well and want them to be a little complicated.

我是 Python 新手,了解不多,但我认为我可以很好地进行测验,并希望它们有点复杂。

How do I make it so that the program will first have the user choose the type of test. (ie. animals or capital cities) and then the questions given to the user will be about that topic. Should I create a function with the set of question for each topic? Then when the user inputs the topic they want, the code should look something like: (roughly)

如何让程序首先让用户选择测试类型。(即动物或首都),然后给用户的问题将与该主题有关。我应该为每个主题创建一个带有一组问题的函数吗?然后当用户输入他们想要的主题时,代码应该看起来像:(大致)

print("Do you want to answer questions on animals or capital cities or math?"
      " Type animal, city or math")
topic = input()
if topic == 'animal':
    def AnimalQuestions(): #this will be written before this code

Is this the correct approach or is there another, more efficient way to do it?

这是正确的方法还是有另一种更有效的方法来做到这一点?

采纳答案by Montaro

I implemented a full example of True and False quiz with multiple questions in each topic, plus validation of the input and aggregation of results, I hope this can be a good example

我实现了一个完整的真假测验的例子,每个主题有多个问题,加上输入的验证和结果的聚合,我希望这可以是一个很好的例子

animals_questions = 'Animals Questions'
capitals_questions = 'Capitals Questions'
math_questions = 'Math Questions'

questions = [animals_questions, capitals_questions, math_questions]

quiz = {animals_questions: [("All lionesses in a pride", True),
                        ("Another animals question", False),
                        ("Last animals question", False)],

        capitals_questions: [("Cairo is the capital city of Egypt", True),
                         ("Another capitals question", True),
                         ("Last capitals question", False)],

        math_questions: [("20 is log 100 for base 1o", False),
                     ("Another math question", True),
                     ("Last math question", False)]
}

result = {"Correct": 0, "Incorrect": 0}

def get_quiz_choice():
    while True:
        try:
            quiz_number = int(raw_input(
                'Choose the quiz you like\n1 for {}\n2 for {}\n3 for {}\nYour choice:'.format(animals_questions,
                                                                                          capitals_questions,
                                                                                          math_questions)))
        except ValueError:
            print "Not a number, please try again\n"
        else:
            if 0 >= quiz_number or quiz_number > len(quiz):
                print "Invalid value, please try again\n"
            else:
                return quiz_number


def get_answer(question, correct_answer):
    while True:
        try:
            print "Q: {}".format(question)
            answer = int(raw_input("1 for True\n0 for False\nYour answer: "))
        except ValueError:
            print "Not a number, please try again\n"
        else:
            if answer is not 0 and answer is not 1:
                print "Invalid value, please try again\n"
            elif bool(answer) is correct_answer:
                result["Correct"] += 1
                return True
            else:
                result["Incorrect"] += 1
                return False


choice = get_quiz_choice()
quiz_name = questions[choice - 1]
print "\nYou chose the {}\n".format(quiz_name)
quiz_questions = quiz[quiz_name]
for q in (quiz_questions):
    print "Your answer is: {}\n".format(str(get_answer(q[0], q[1])))

The output is something like:

输出类似于:

/usr/bin/python /Users/arefaey/workspace/playground/python/Quiz/quiz.py

Choose the quiz you like
1 for Animals Questions
2 for Capitals Questions
3 for Math Questions
Your choice: 2

You chose the Capitals Questions

Q: Cairo is the capital city of Egypt
1 for True
0 for False
Your answer: 1
Your answer is: True

Q: Another capitals question
1 for True
0 for False
Your answer: 1
Your answer is: True

Q: Last capitals question
1 for True
0 for False
Your answer: 1
Your answer is: False

You have finished the quiz with score: {'Incorrect': 1, 'Correct': 2}

回答by Karl

This should get you on the right track, however judging by your code example it may pay to have a read through the Pythondocumentation and/or have a go at some of the tutorial material @ http://www.learnpython.org/

这应该会让你走上正确的轨道,但是从你的代码示例来看,通读Python文档和/或尝试一些教程材料 @ http://www.learnpython.org/可能是值得的

def animal_quiz():
    # do something

def city_quiz():
    # do something

def math_quiz():
    # do something

topic = raw_input('Do you want to answer questions on animals or capital cities or math? Type animal, city or math')
if topic == 'animal':
    animal_quiz()
elif topic == 'city':
    city_quiz()
elif topic == 'math':
    math_quiz()