简体   繁体   中英

Don't understand why this AttributeError occurs in for loop

I need help for the small quiz game I am writing for a school project. The is supposed to have 3 questions with multiple choices. It is written in OOP Python 3. It is my first time working with Python classes.

Here is the code:

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

q_dict = [
    """Q1 Why is it important to scan your target network slowly?\n
    A. To avoid alerting the IDS
    B. It is not necessary to scan the network slowly."""'\n\n\n',

    """Q2 What is the difference between a traditional firewall and an IPS?
    A. Firewalls do not generate logs.
    D. IPS can dissect packets"""'\n\n\n',

    """Q3 What tool is able to conduct a man-in-the-Middle Attack on an 802.3 environment?
    A. Ettercap
    B. Cain & Abel"""'\n\n\n'
]

a_dict = [
    Questions(q_dict[0], "A"),
    Questions(q_dict[1], "D"),
    Questions(q_dict[2], "B")
]

def start(a_dict):
    points = 0
    for question in a_dict:
        answer = input(q_dict.question)
        if answer == a_dict.answer:
            points += 10
    print("You got 10 points")
    print("Total points: %s" % points)

start(a_dict)

My program throws an error when I try to run it:

Traceback (most recent call last):
  File "./test.py", line 36, in <module>
    start(a_dict)
  File "./test.py", line 30, in start
    answer = input(a_dict.question)
AttributeError: 'list' object has no attribute 'question'

I want it to print the list and prompt the user to enter their choice and if the answer matches what I set as the correct answer to give the user 10 points and then display the total points.

You are iterating over your list that contains the Question objects. So you would need to write:

for question in a_dict:
    answer = input(question.question)
    if answer == question.answer:
        points += 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM