John Rougeux
John Rougeux

Reputation: 11

"None" given when attempting to return the value of dict in Python

I'm trying to return the values of a dict when creating an instance of a class in Python, but I keep getting "None" returned instead.

I'm very new to Python, so I'm sure there is an easy answer to this one.

After running the below:

class TestTwo(object):

    def __init__(self):
            self.attributes = {
            'age': "",
            'name' : "",
            'location': ""
    }

    def your_age(self):
        self.attributes['age'] = raw_input("What is your age? > ")
        self.your_name()

    def your_name(self):
        self.attributes['name'] = raw_input("What is your name? > ")
        self.your_location()

    def your_location(self):
        self.attributes['location'] = raw_input("Where do you live? > ")
        self.results()

    def results(self):
        print "You live in %s" % self.attributes['location']
        print "Your number is %s" % self.attributes['age']
        print "Your name is %s" % self.attributes['name']
        d = self.attributes
        return d

output = TestTwo().your_age()
print output

I end up with this:

MacBook-Pro-2:python johnrougeux$ python class_test.py
What is your age? > 30
What is your name? > John
Where do you live? > KY
You live in KY
Your number is 30
Your name is John
None

Instead of "None", I was expecting "{'age': '30', 'name': 'John', 'location': 'KY'}"

What am I missing?

Upvotes: 1

Views: 124

Answers (2)

tovmeod
tovmeod

Reputation: 888

the function your_age() doesn't return any values, of course output is None

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318548

Only results() returns something. You need to pass its return value along the call chain by returning it in the other functions if you want them to return something, too:

def your_age(self):
    self.attributes['age'] = raw_input("What is your age? > ")
    return self.your_name()

def your_name(self):
    self.attributes['name'] = raw_input("What is your name? > ")
    return self.your_location()

def your_location(self):
    self.attributes['location'] = raw_input("Where do you live? > ")
    return self.results()

Of course this kind of chaining is extremely ugly; but I'm sure you already know that. If not, rewrite your code like this:

in each of those functions, just set the value and do not call one of your other functions. Then add a function such as this:

def prompt_data(self):
    self.your_age()
    self.your_name()
    self.your_location()

In the code using the class, do this:

t2 = TestTwo()
t2.prompt_data()
output = t2.results()

Upvotes: 6

Related Questions