Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Unexpected output
#1
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
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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.
Reply
#4
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#5
Got that, thank you so much.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Unexpected output Starter 2 476 Nov-22-2023, 12:08 AM
Last Post: Starter
  Unexpected Output - Python Dataframes: Filtering based on Overlapping Dates Xensor 5 702 Nov-15-2023, 06:54 PM
Last Post: deanhystad
  Unexpected output while using random.randint with def terickson2367 1 508 Oct-24-2023, 05:56 AM
Last Post: buran
  Unexpected output from df.loc when indexing by label idratherbecoding 6 1,186 Apr-19-2023, 12:11 AM
Last Post: deanhystad
  unexpected output asyrafcc99 0 1,500 Oct-24-2020, 02:40 PM
Last Post: asyrafcc99
  Unexpected output: symbols for derivative not being displayed saucerdesigner 0 2,045 Jun-22-2020, 10:06 PM
Last Post: saucerdesigner
  Unexpected output: if statement CabbageMan 1 1,760 Sep-04-2019, 04:12 PM
Last Post: ThomasL
  Unexpected Output using classes and inheritance langley 2 1,944 Jul-04-2019, 09:33 AM
Last Post: langley
  float multiplication - unexpected output inesk 3 3,324 Dec-11-2018, 10:59 AM
Last Post: DeaD_EyE
  Unexpected output when searching for a string from os.popen output FujiJean 3 3,073 Oct-02-2018, 11:39 AM
Last Post: volcano63

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020