Ikiro
Ikiro

Reputation: 47

Python 3.x: Object Not Accepting Definition?

Ok, so I have this class that's supposed to have food, hunger, and some other attributes.

I have just a definition like this:

def setfood():
     choice = input("Choice: ")
     if choice == "1":
           food = 1
           bored = 2
     if choice == "2":
           food = 4
           bored = 8
     return food
     return bored

And then I have this class like this.

class thing(object):
    def __init__(self, name, hunger = 0, boredom = 0):
        self.name = name
        self.hunger = hunger
        self.boredom = boredom

    def eat(self):
       setfood()
       self.hunger -= food
       self.boredom += bored

Well, no matter what I do, I can't get it to work. I kept getting this error about a global variable.

Well, I add in food = 0 and bored = 0 into the main part of the program and it makes no difference because I can't pass the global variables into the definition.

I tried to add the definition into my class and it still made no difference. I also tried to make separate definitions to return each variables...also didn't work. No matter what I do, I can't win.

The only way I can get it to work is if I do this:

food = setfood()

I thought I could maybe change it to this:

food = setfood(food)
food = setfood(bored)

But that doesn't work either...

But, if I do that for both variables, I have to go through the whole thing twice. So what exactly do I do? I'm so lost and frustrated.

Upvotes: 0

Views: 63

Answers (2)

Doug T.
Doug T.

Reputation: 65619

"NameError: global name 'food' is not defined"

food in your function is only defined when you enter one of the if blocks. Are you entering input other than 1 or 2? If os food won't be defined to anything. You could have a default value for food like:

food = 0 # food stays at 0 for invalid choices
choice = input("Choice: ")
if choice == "1":
     food = 1
     bored = 2
if choice == "2":
     food = 4
     bored = 8
return food

Also to return two variables your return statements need to return a tuple, ie

 return (food, bored)

then the caller can do

 (food, bored) = setfood()

and you'll be able to return two values at once as you intend

Upvotes: 1

Frantz Romain
Frantz Romain

Reputation: 846

def setfood(): 

Is a set method. It should not have to return anything. You should define other methods like getfood() or getboredStatus() to return food status or bored status. See here for more info

Upvotes: 0

Related Questions