Python Forum

Full Version: "not defined" error in function referencing a class
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Question.py
class Question:
    def __init__(self, prompt, answer):
        self.prompt = prompt
        self.answer = answer
scratch.py
from Question import Question


question_prompts = [
    "What does nauta mean?\n(a) man\n(b) sailor\n(c) poet\n(d) farmer",
    "What does poeta mean?\n(a) man\n(b) sailor\n(c) poet\n(d) farmer",
    "What does agricola mean?\n(a) man\n(b) sailor\n(c) poet\n(d) farmer"
]

questions = [
    Question(question_prompts[0], "b"),
    Question(question_prompts[1], "c"),
    Question(question_prompts[2], "d")
]

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

run_test(questions)
I'm getting an error saying that "question.prompt" and "question.answer" are not defined, but I'm using the exact same code from this video tutorial, and it's not working for me.
each time the for loop loops it is using each_question so you need to change the following question's to each_question

def run_test(questions):
    score = 0
    for each_question in questions:
        answer = input(each_question.prompt)
        if answer == each_question.answer:
            score += 1
    print("You got " + str(score) + "/" + str(len(questions)) + " correct.")
In the video
for question in questions:
was used
def run_test(questions):
    score = 0
    for question in questions:
        answer = input(question.prompt)
        if answer == question.answer:
            score += 1
    print("You got " + str(score) + "/" + str(len(questions)) + " correct.")
(Mar-27-2019, 11:58 PM)Yoriz Wrote: [ -> ]each time the for loop loops it is using each_question so you need to change the following question's to each_question

def run_test(questions):
    score = 0
    for each_question in questions:
        answer = input(each_question.prompt)
        if answer == each_question.answer:
            score += 1
    print("You got " + str(score) + "/" + str(len(questions)) + " correct.")

Oh, I'm an idiot. Thank you so much!