Python Forum
"not defined" error in function referencing a class - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: "not defined" error in function referencing a class (/thread-17087.html)



"not defined" error in function referencing a class - Exsul - Mar-27-2019

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.


RE: "not defined" error in function referencing a class - Yoriz - Mar-27-2019

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.")



RE: "not defined" error in function referencing a class - Exsul - Mar-27-2019

(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!