如何使用字典而不是大量的if / else语句在Python中创建测验?

时间:2016-01-11 15:12:00

标签: python python-2.7 loops dictionary

我正在进行是/否问题的答案,其中回答是/否取决于问题奖励不同数量的积分,每个积分将被添加到总数中并在最后显示。

然而,测验中有大约50个问题,这意味着大量的if / else语句。有没有办法可以使用字典和循环或类似的东西来显着缩短程序的长度?

编辑这种重复多次是我想要避免的。我正在考虑添加变量i并在每个问题后添加1,并查找下一个问题的索引。但这只能用列表来实现吗?

div

6 个答案:

答案 0 :(得分:3)

创建词典列表。每个元素都是一个问题,是和否的要点。然后,您可以轻松地遍历列表。

qa = [{"question": "Do you exercise?", "yes": 10, "no": 0},
       "question": "Do you smoke?", "yes": -10, "no": 0},
       ...
     ]
for item in qa.items():
    answer = raw_input("Do you exercise daily? ")
    score = item.get(answer)
    total = total + score

当然,您需要添加一些额外的代码来处理用户没有按字面意思回答的情况"是"或"不",但这不会影响此解决方案。关键是,您创建一个表示问题的对象,以及可能的分数答案,然后迭代这些对象的列表。

您甚至可以更进一步创建自定义类。你可以这样做,例如:

class Question(object):
    def __init__(self, question, yes=0, no=0):
        self.question = question
        self.yes = yes
        self.no = no

questions = [Question("Do you exercise?", yes=10, no=0),
             Question("Do you smoke?", yes=0, no=-10),
             ...
            ]

for question in questions:
    answer = raw_input(question.question)
    ...

答案 1 :(得分:3)

在最低级别,使用您给出的示例,您真正需要的只是一个要问的问题列表,然后循环遍历

print "The following are y/n questions."
total = 0 

questions = ["Do you exercise daily? ", "Is this a second question?"]

for question in questions:
    q1 = raw_input(question)
    if q1 == "y":
        total += 1

print total

当然,这可以扩展为包含适当的对象类等等。

  

我正在考虑使用这种方法,但是,如何为每个问题绑定不同的点值?一个问题可能值六,而另一个可能值四。我可以制作包含点值的第二个列表吗?

您创建一个问题类,然后将列表列为这些答案的列表

class Question()
    def __init__(self, text, correct_answer_value)
        this.text = text
        this.value = correct_answer_value

print "The following are y/n questions."
total = 0 

questions = [Question("Do you exercise daily? ",1), Question("Is this a second question?",2)]

for question in questions:
    q1 = raw_input(question.text)
    if q1 == "y":
        total += question.value

print total

答案 2 :(得分:1)

# Firstly, declare your questions. Create it with their answer and associated score.
questions = {}
questions[1] = {}
questions[1]["question"] = "Is the sky blue? Y/N"
questions[1]["answer"] = True
questions[1]["score"] = 50

# We can add more questions
questions[2] = {}
questions[2]["question"] = "Is Python a programming language? Y/N"
questions[2]["answer"] = True
questions[2]["score"] = 150

# Set the initial score at 0
score = 0

# Loop over the questions
for key in questions:
    user_answer = None

    # We ask the question till the user answer Yes or Not
    while user_answer not in ["Y","N"]:
        user_answer = raw_input(questions[key]["question"])

    # If the user said Yes we keep True, if he said No we keep False
    user_answer = True if user_answer == "Y" else False 

    # We increment the score if the answer is the same that it's stored in your dictionary
    score += questions[key]["score"] if user_answer == questions[key]["answer"] else 0

print "Final score {0}".format(score)

答案 3 :(得分:1)

一些设置代码,比如

def get_yesno(prompt):
    while True:
        response = raw_input(prompt).strip().lower()
        if response in {'y', 'yes'}:
            return True
        elif response in {'n', 'no'}:
            return False
        else:
            print("Please respond with yes or no.")

class YesNo:
    __slots__ = ('question', 'yes_points', 'no_points')

    def __init__(self, question, yes_points=1, no_points=0):
        self.question = question
        self.yes_points = yes_points
        self.no_points = no_points

    def ask(self):
        if get_yesno(self.question):
            return self.yes_points
        else:
            return self.no_points

表示您可以轻松定义

等问题
questions = [
    YesNo("Do you exercise daily? "),
    YesNo("Do you have more than 3 drinks a week? ", -5, 2)
]

然后您的主程序变为

def main():
    score = sum(q.ask() for q in questions)
    print("Your score was {}".format(score))

if __name__ == "__main__":
    main()

答案 4 :(得分:0)

将您的问题添加到列表中。 (Lists

然后简单地使用:

for question in questionList:
    q1 = raw_input(question)
    if q1 == "y":
        total += 1
    else:
        total = total
print total

答案 5 :(得分:0)

你特别提到你想使用字典,所以这个答案将提供一个如何做到这一点的解决方案。

如果您只是希望答案是'是' /' no',那么您可以按如下方式设置字典:

test_dict = {'question1': {'yes': 100, 'no': 50}, 
             'question2': {'yes': 75, 'no': 25}}

然后你可以提出问题,抓住他们的答案,然后通过字典传递它们以积累他们的分数。

question1_ans = raw_input("Is your favorite animal a Rhino?").lower()

num_points += test_dict['question1'][question1_ans]

在这种情况下,如果您回答“是”,那么num_points将为100.否则,回答“否”将导致num_points为50。

显然,这并不能阻止他们回答:" FOO"而不是'是' no',这会导致一个KeyError。