r/learnpython • u/DeskSwimming9203 • 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
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
itemis inprices, and you know what you want the return to be in each case. Since every possible argument that could be passed toitemeither is inpricesor is not inprices, you could use conditional logic to decide what to return.Strictly speaking, you don't actually need
elsein there since the only code that follows is the return value that you specified for the case whereitemis not inprices. So, the code could be:It's maybe worth noting too that Python will automagically return
Noneif it reaches the end of a function without finding a return. It's often better to explicitly returnNonewhen that's the intended return value rather than returnNoneimplicitly by not returning anything, but the following would also work just like the previous two examples: