Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Basic Object-Oriented Python Welcome to OOP Adding to our Panda

Angelus Miculek
Angelus Miculek
3,859 Points

bao bao bugged ('adding to our panda' code objectives)

I am on task two, and am stupidly stuck. The quiz may be malfunctioning; it repeatedly just says Bummer: NameError: name 'name' is not defined. My code is this:

class Panda:
    species = 'Ailuropoda melanoleuca'
    #name = 'Bao Bao'
    food = 'bamboo'

    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.is_hungry = True

    def eat(self):
        self.is_hungry = False
        #self.name = 'Bao Bao'
        #self.food = 'bamboo'
        return '{} eats {}.'.format(name, food)

#pan = Panda('Bao Bao', 2)
#pan.eat()

The commented lines are all the methods (pun not intended)--and combinations thereof--I have tried, yet nothing works. Is bao bao too much for me, or is the system bugged from the start? I need help, please.

2 Answers

Rohald van Merode
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Rohald van Merode
Treehouse Staff

Hey Angelus Miculek 👋

This error is caused by your return statement in the eat method. Overall it looks great, but the name and food variables are not defined. Python interprets the name as a local variable within the method, if no such local variable is defined, it will look for it in the global scope where this variable isn't defined either.

Instead, you'll want to use the instance variable of the Panda object, you can do so by using self.name instead. Same goes for the food variable where you'll want to pass self.food to access the Panda class variable.

def eat(self):
        self.is_hungry = False
        return '{} eats {}.'.format(self.name, self.food)

After these quick fixes your code should pass the challenge as expected 🎉

Hope this helps!

Angelus Miculek
Angelus Miculek
3,859 Points

Thank you Rohald!!! It seems so simple now!