创建对象列表python

我正在尝试创建测验,并且questions第二元素的数组中存在语法错误。我试图通过`for循环将每个对象附加到数组,但是我需要每个问题都有正确的答案。


Questions 类位于不同的文件中:


class Questions:

    def __init__(self, prompt, answer):

        self.prompt = prompt

        self.answer = answer

这是主文件:


from Questions import Questions

questionsPrompt = ["What does CPU stand for?\n(a) central procesing unit\n(b)controlled purification\n(c)computer unit",

    "What is an advantage of a compiler?\n(a)slow to run each time\n(b)compiling takes a long time\n(c)easy to implement",

    "The Operating System is a :\n(a)system software\n(b)application software\n(c)utility software"]


questions = [

    Questions(questionsPrompt[0], "a")

    Questions(questionsPrompt[1], "b")

    Questions(questionsPrompt[2], "a")

]


def runQuiz(questions):

    score = 0

    for question in questions:

        answer = input(question.prompt)

        if answer == question.answer:

            score += 1

    return score


runQuiz(questions)


qq_遁去的一_1
浏览 147回答 2
2回答

开满天机

正如 Aran-Fey 评论的那样,列表项必须用逗号分隔。对于字典、集合等其他集合也是如此。questions = [    Questions(questionsPrompt[0], "a"),    Questions(questionsPrompt[1], "b"),    Questions(questionsPrompt[2], "a")]

鸿蒙传说

正如 Aran-Fey 指出的那样,您的语法不正确。questions = [    Questions(questionsPrompt[0], "a"),    Questions(questionsPrompt[1], "b"),    Questions(questionsPrompt[2], "a")]另外,还有一点,您正在创建的是一个列表,而不是一个数组。语义和实现都存在差异,而且由于 Python 两者都有,所以这是一个重要的区别。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python