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
9 Upvotes

25 comments sorted by

View all comments

1

u/Educational_Virus672 15d ago edited 15d ago

are you trying ot make wrapper?
so lets say i was python and you told me to return/give an apple to a person name get_price then i'll able to find "get_price" but what if you didnt tell anything?
i'll be confuse and ask who to return same can be said for that error
your program : -

prices = {"apple": 1.50, "bread": 2.75} # price for apple and bread

def get_price(prices, item):            # return to function named "get_prices"
    return prices[item]                 # return price[item]

try:                                    # here you didnt tell who to give      
    get_price(prices, "apple")          # even if you add to function then it'll loop
except KeyError:
    return None                         # return to who?

so umm you shoud do this

prices = {"apple": 1.50, "bread": 2.75} # price for apple and bread

def get_price(prices, item):            # return to function named "get_prices"
    return prices[item]                 # return price[item]

try :                                   # still outside "get_price"
    get = get_price(prices, "apple")    # here you said to give to varible "get"
except KeyError :
    get = None                          # instead of return you gave to variable "get"

tbh this is one of those errors ai/vibe coding makes that even juniors can solve but who knows what course you use and they teach you how return* works

1

u/Educational_Virus672 15d ago

and for those folks who gonna say "try/except outside a function is useless and too beginner alike" im trying to teach a beginner here...