Daz Daz - 2 months ago 21
Python Question

Simple python class not working

I'm having some trouble with this class in Python, why is it not working?

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

def yesno(self):
if self.answer == self.question:
return str("Correct!")
else:
return str("Wrong!")

print("Time for a quiz.")

print("What is ((((6^2 * 10) + sqrt((5000*3) - 600)) / 4! ) * 4 ) - log(1 * 10^11)?")
userAnswer = int(input())
question1 = Quiz(userAnswer, 69)
Quiz.yesno()

Answer

Yep, you need to instantiate the class. So, question1.yesno() is the right way to go when calling the method (you're calling a method on the instance of the object).

Also, you have a small indentation error that could cause some problems further down the road.

def yesno(self):
        if self.answer == self.question:
        return str("Correct!")
    else:
        return str("Wrong!")

Should actually be:

def yesno(self):
            if self.answer == self.question:
               return str("Correct!")
            else:
               return str("Wrong!")