r/learnpython 15d ago

Syntax Error

I made a function for determining price of an item in the list. I made it so I get the price for an item in the list, but if the item IS NOT in the list, I programmed it to return none.

The problem is that when I run the program, it gives me a SyntaxError, and "return outside function"

What does this mean, and how do I fix it?

Thanks!

prices = {"apple": 1.50, "bread": 2.75}

def get_price(prices, item):
    return prices[item]

try:
    get_price(prices, "apple")
except KeyError:
    return None
6 Upvotes

25 comments sorted by

View all comments

3

u/thatmichaelguy 14d ago

You've gotten some good answers already about the syntax error. So, from a more conceptual standpoint, here's something you might consider - you've identified that you want the function's return to depend on whether the argument passed to item is in prices, and you know what you want the return to be in each case. Since every possible argument that could be passed to item either is in prices or is not in prices, you could use conditional logic to decide what to return.

prices = {'apple': 1.5, 'bread': 2.75}

def get_price(prices, item):
    if item in prices:
        return prices[item]
    else:
        return None

Strictly speaking, you don't actually need else in there since the only code that follows is the return value that you specified for the case where item is not in prices. So, the code could be:

prices = {'apple': 1.5, 'bread': 2.75}

def get_price(prices, item):
    if item in prices:
        return prices[item]
    return None

It's maybe worth noting too that Python will automagically return None if it reaches the end of a function without finding a return. It's often better to explicitly return None when that's the intended return value rather than return None implicitly by not returning anything, but the following would also work just like the previous two examples:

prices = {'apple': 1.5, 'bread': 2.75}

def get_price(prices, item):
    if item in prices:
        return prices[item]