Search code examples
pythonattributesattributeerrorpython-class

AttributeError: 'list' object has no attribute 'question' on Python


I met with the following issue AttributeError, but I have checked the syntax and indentation, and found no mistakes. Can anyone help me figure out what went wrong?

class Question():
    def __init__(self, question, answer):
        self.question = question
        self.answer = answer

question_prompts = [
    "What color are apples?\n(a) Red/Green\n(b) Purple\n(c) Orange\n",
    "What color are bananas?\n(a) Teal\n(b) Magenta\n(c) Yellow\n",
    "What color are strawberries?\n(a) Yellow\n(b) Red\n(c) Blue\n",
]

tasks = [
    Question(question_prompts[0], "a"),
    Question(question_prompts[1], "c"),
    Question(question_prompts[2], "b"),
]

def run_test(tasks):
    score = 0
    for items in tasks:
        answer = input(tasks.question)
        if answer == tasks.answer:
            score += 1
    print("You got " + str(score) + "/" + str(len(question_prompts)) + " correct")

run_test(tasks)

Exception:

AttributeError: 'list' object has no attribute 'question'

Solution

  • You're looking at the entire list of Questions and trying to index the .question attribute so it looks at the list container instead of the individual object, this would be fixed by :-

    answer = input(items.question)
    

    As items is the variable containing the Question object on each pass of the loop. You'll have to change the answer check accordingly as well