user3339203
user3339203

Reputation: 133

How to return values with the return statement in python?

I'm writing a program that returns the train prices. When I run the function nothing is returning.

def transit(zone, ticket):
    fareLst = ['23', '11.5', '34.5']

    if zone < 2 and ticket == 'adult':
        return fareLst[0]

    elif zone < 2 and ticket == 'child':
        return fareLst[1]

    elif zone > 4 and ticket == 'adult':
         return -1


def main():
    transit(1, 'adult')   # the function is not returning the fareLst = 23


main()

Upvotes: 0

Views: 98

Answers (3)

xbb
xbb

Reputation: 2163

If you only want to just print out the result, do the following:

def main():
    print transit(1,'adult')

or if you want to store the variable and print it later, do the following:

def main():
    result = transit(1,'adult')
    #do something
    print result

Upvotes: 2

Erik Kaplun
Erik Kaplun

Reputation: 38257

The function is returning the value; you're just not doing anything with it. You can print it if you want:

def main():
    print transit(1, 'adult')

return is not the same as printing something on the screen; return values are used like this, for example:

smth = transit(1, 'adult')

You don't want everything that you ever return to be printed out automatically.


Also, on another note, you should use proper floating point values to store floating point data, instead of strings:

fareLst = [23.0, 11.5, 34.5]

Also, note that if you call transit(5, 'child'), it will return nothing/None... so you might want this at the end of your if-elif block:

else:
    return -1

instead of:

elif zone > 4 and ticket == 'adult':
     return -1

...although None might also be a viable option for e.g. completely invalid input; but then again, an exception would be even better in that case.

Upvotes: 5

Kirk Strauser
Kirk Strauser

Reputation: 30977

Others have already mentioned that you're not storing the return value, but I'll also add that you have no default "base case" at the end. In this code:

def transit(zone, ticket):
    fareLst = ['23', '11.5', '34.5']

    if zone < 2 and ticket == 'adult':
        return fareLst[0]

    elif zone < 2 and ticket == 'child':
        return fareLst[1]

    elif zone > 4 and ticket == 'adult':
         return -1

what if zone is equal to 2, 3, or 4? What if zone is 4 but ticket is child? All of those would fall through to the end, and the default return value of a function is None. That's probably not what you want. If not, add something like return 20 or whatever a sensible default ticket price would be.

Also, it's not Pythonic to return sentinel values like in the final case above. A more Pythonic approach would be to raise a ValueError if the parameters are bad, then wrap your calling code in a try/except block. That leaves no room for ambiguity, and checking return values is a pain in the neck.

Upvotes: 0

Related Questions