I thought that if an attribute was give 'self.' then even if the attribute wasn't set up in a method, it could be used in other methods. However, I keep getting this error:
AttributeError: 'QuizBrain' object has no attribute 'user_r'
this is my full code:
question_data = [
{"text": "A slug's blood is green.", "answer": "True"},
{"text": "The loudest animal is the African Elephant.", "answer": "False"},
{"text": "Approximately one quarter of human bones are in the feet.", "answer": "True"},
{"text": "The total surface area of a human lungs is the size of a football pitch.", "answer": "True"},
{"text": "In West Virginia, USA, if you accidentally hit an animal with your car, you are free to take it home to eat.", "answer": "True"},
{"text": "In London, UK, if you happen to die in the House of Parliament, you are entitled to a state funeral.", "answer": "False"},
{"text": "It is illegal to pee in the Ocean in Portugal.", "answer": "True"},
{"text": "You can lead a cow down stairs but not up stairs.", "answer": "False"},
{"text": "Google was originally called 'Backrub'.", "answer": "True"},
{"text": "Buzz Aldrin's mother's maiden name was 'Moon'.", "answer": "True"},
{"text": "No piece of square dry paper can be folded in half more than 7 times.",
"answer": "False"},
{"text": "A few ounces of chocolate can to kill a small dog.", "answer": "True"}
]
class QuizBrain:
def __init__(self, q_list, a_list):
self.question_list = q_list
self.answer_list = a_list
self.current_number = 0
def next_question(self):
question = self.question_list[self.current_number]
context_question_number = self.current_number 1
self.user_r = input(
(f'Q.{context_question_number}: {question} True or False '))
self.current_number = 1
def still_have_questions(self):
return(self.current_number < len(self.question_list))
def check_answer(self):
self.current_answer = self.answer_list[self.current_number]
if self.user_r == self.current_answer:
return True
elif self.user_r != self.current_answer:
print(
"the answer is {}, you got {} questions right" .format(self.current_answer, self.current_number))
return False
list_of_questions = []
list_of_answers = []
for line in question_data:
question_line = line['text']
list_of_questions.append(question_line)
for line in question_data:
answer_line = line['answer']
list_of_answers.append(answer_line)
quiz_brain = QuizBrain(list_of_questions, list_of_answers)
while quiz_brain.still_have_questions() and quiz_brain.check_answer():
quiz_brain.next_question()
quiz_brain.check_answer()
Do I have to mention the user_r attribute in the init part?
CodePudding user response:
You are calling check_answer
, which tries to read self.user_r
, before you have called next_question
, which writes self.user_r
.
Here is a way you can avoid calling check_answer
before you have called next_question
:
while quiz_brain.still_have_questions():
quiz_brain.next_question()
if not quiz_brain.check_answer():
break