Python Forum

Full Version: Unexpected output
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm trying to create a class to output a zipped list for other classes to use. This is the code:

class Epworthquestions():


    print("This is the Epworth sleepiness scale. ")
    print("How likely are you to doze off or fall asleep in the following situations? 0 = never, 1= slight chance, 2= moderate chance, 3= high chance of dozing. ")

    q1 =  "Sitting and reading? "
    q2 =  "Watching TV? "
    q3 =  "Sitting, inactive in a public place? "
    q4 =  "As a passenger in a car for an hour without break? "
    q5 =  "Lying down to rest in the afternoon when circumstances permit? "
    q6 =  "Sitting and talking to someone? "
    q7 =  "Stiing quietly after a lunch without alcohol? "
    q8 =  "Driving in a car, while stopped for a few minutes in the traffic? "

    questions = [q1,q2,q3,q4,q5,q6,q7,q8]
    answer = []

    def Epworth():

        for question in Epworthquestions.questions:
            while True:
                a = input(question)
                try:
                    ans = int(a)
                except ValueError:
                    print("Please enter a number. ")
                    continue
                if ans not in range(0,4):
                    print("Please enter a number between 0 and 4")
                else:
                    Epworthquestions.answer.append(ans)
                    break

        for q,a in zip(Epworthquestions.questions,Epworthquestions.answer):
            c = [q,a]
        return  c


x = Epworthquestions.Epworth()
print(x)
I needed the function Epworth() to output the whole list of questions and answers but all I get is the last question and answer:

Output:
This is the Epworth sleepiness scale. How likely are you to doze off or fall asleep in the following situations? 0 = never, 1= slight chance, 2= moderate chance, 3= high chance of dozing. Sitting and reading? 0 Watching TV? 0 Sitting, inactive in a public place? 0 As a passenger in a car for an hour without break? 0 Lying down to rest in the afternoon when circumstances permit? 0 Sitting and talking to someone? 0 Stiing quietly after a lunch without alcohol? 0 Driving in a car, while stopped for a few minutes in the traffic? 0 ['Driving in a car, while stopped for a few minutes in the traffic? ', 0]
What am I missing here?

Thanks for your help in advance
Your problem is here:

        for q,a in zip(Epworthquestions.questions,Epworthquestions.answer):
            c = [q,a]
        return  c
Every time through the loop, you overwrite c with one question/answer pair. You should start with an empty list, and append a tuple of (q, a) to that list each time through the loop.

Also, your use of classes is very odd. You should really be making an instance of the class. You might want to check out our basic class tutorial.
Thanks.

I read the tutorials and tried to refactor my code, but still run into an Attribute Error.

Code:
class EpworthAnswers(object):
    """Gets end user to input answers to the questions"""
    """Stores answers in answerlist to be used by other classes"""

    answerlist = []
    def __init__(self,questions):
        self.questions = questions

    def answers(self):
            while True:
               a = input(self.questions)
               try:
                   ans = int(a)
               except ValueError:
                   print("Please enter a number. ")
                   continue
               if ans not in range(0,8):
                   print("Please enter a number between 0 and 4")
               else:
                   EpworthAnswers.answerlist.append(ans)
                   break
               return EpworthAnswers.answerlist

a = "Question 1"
b = "Question 2"
x = "Questoon 3"  #subset of questions
c = [a,b,x]
for i in c:
    EpworthAnswers.answers(i)
d = sum(EpworthAnswers.answerlist)
print(d)
Output:
Output:
Traceback (most recent call last): File "epworth4.py", line 29, in <module> EpworthAnswers.answers(i) File "epworth4.py", line 11, in answers a = input(self.questions) AttributeError: 'str' object has no attribute 'questions'
What does the last line of the traceback even mean..?

Thanks again for your help.
You are still using the class itself, rather than making an instance of the class. Since you never make an instance, __init__ is never called, and there is no self or self.questions defined. Here's how you would do it with creating an instance:

class EpworthAnswers(object):
    """Gets end user to input answers to the questions"""
    """Stores answers in answerlist to be used by other classes"""

    def __init__(self,questions):
        self.questions = questions
        # make answer_list an instance variable, so each instance can have different answers.
        self.answer_list = []

    def answers(self):
        for question in self.questions:   # loop through the stored questions
            while True:
                answer = input(question)
                try:
                   number = int(answer)
                except ValueError:
                   print("Please enter a number. ")
                   continue
                if not (0 <= number <= 8):                          # more efficient
                   print("Please enter a number between 0 and 4")
                else:
                   self.answer_list.append(number)
                   break
        return self.answer_list    # You could get rid of this, not currently using the return value.

a = "Question 1"
b = "Question 2"
x = "Questoon 3"  #subset of questions
test = EpworthAnswers([a,b,x])     # create an instance, providing questions as parameter to __init__
test.answers()                     # the instance does the loop, you don't need to remember what the questons are.
d = sum(test.answer_list)          # get the instance attribute for the total (could be a method)
print(d)
Note that when I call test.answers() on line 30, I am not providing the self parameter. The self parameter is the instance itself, and that parameter is provided automatically by Python when you call a method of an instance.
Got that, thank you so much.