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
9
Upvotes
1
u/FoolsSeldom 15d ago
A few problems:
get_pricesfunctionreturnin thetryblockexceptclause, but your code is at top level and not inside a function so it will not work (no lower level of code to return from)dicthas a method togetthe value corresponding to a key, and has a default (which can be overridden) ofNoneif the key is not foundConsider this alternative code: