user3251511
user3251511

Reputation: 187

Class in Python error

Below is the test cases and after that is my code

What I need is to correct is my error within self.teach. In the test cases below, my code states " meow meow says meowpurr" when the correct one is " meow meow says meow and purr". The other test cases are correct.

     #test cases    
meow_meow = Tamagotchi("meow meow")
meow_meow.teach("meow")
meow_meow.play()
>>>>"meow meow says meow"
meow_meow.teach("purr")
meow_meow.teach("meow")
meow_meow.play()
>>>>'meow meow says meow and purr'  #My own code state " meow meow says meowpurr" 

Using my code:

class Tamagotchi(object):
    def __init__(self, name):
        self.name = name
        self.words = str(self.name) + " says "
        #check alive, dead within all the methods
        self.alive = True

   #trouble portion
   def teach(self, *words):
        if self.alive == False:
            self.words = self.name + " is pining for the fjords"
            return self.words
        else:
            listing = []
            for word in words:
                listing.append(str(word))
            B = " and ".join(listing)
            self.words += B


    def play(self):
        return self.words
    def kill(self):
        if self.alive == True:
            self.words = self.name + " is pining for the fjords"
            self.alive = False
            return self.name + " killed"
        else:
            return self.name + " is pining for the fjords"

Thanks

Upvotes: 2

Views: 94

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121924

Don't store words as a string; store it as a list instead and only join the list with ' and ' when running .play(); this is also where you'd test if your tamagotchi is still alive:

class Tamagotchi(object):
    def __init__(self, name):
        self.name = name
        self.words = []
        self.alive = True

    def teach(self, *words):
        self.words.extend(words)    

    def kill(self):
        self.alive = False

    def play(self):
        if self.alive:
            return '{} says {}'.format(self.name, ' and '.join(self.words))
        else:
            return '{} is pining for the fjords'.format(self.name)

Your test cases don't seem to need Tamagotchi.teach() and Tamagotchi.kill() to return anything.

Upvotes: 2

Related Questions