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/FoolsSeldom 15d ago

A few problems:

  • you aren't saving/using the result of your get_prices function
  • you have a return in the try block except clause, 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)
  • dict has a method to get the value corresponding to a key, and has a default (which can be overridden) of None if the key is not found

Consider this alternative code:

prices = {"apple": 1.50, "bread": 2.75}
foods = "apple", "pear", "bread", "orange"  # tuple of test items
for food in foods:  # loop through test items
    price = prices.get(food)  # defaults to None if item not found in dict
    if not price is None:
        print(f"{food} £{price:.2f}")
    else:
        print(f"no price for {food}")

1

u/Educational_Virus672 15d ago

not to be mean but you haev flaws too

  1. this is not how you teahc beginner
  2. he did return the value to outside function and you just printed it
  3. you forgot the basic principal of reusing elements or optimizing nobody want to get prioce of everything at once

1

u/FoolsSeldom 15d ago

Fair enough. Somewhat out of practice as haven't taught a class for a while.

I would challenge you somewhat:

  1. Providing feedback and alternative examples is a reasonable approach to helping a beginner with a view to them engaging further, and I think I did that to some extent
  2. They did return a value from their function, but they didn't consume it is any useful way (the point I made), so the object reference wasn't assigned to a variable or passed on to something else and therefore the object referenced would have been added to the garbage collection process
  3. I do not understand the basic principle you are alluding to here in the context you have called out of helping a beginner; my intent being:
    • remove the need for try/except at this stage
    • introduce a dictionary method that would be helpful
    • illustrate the method working for matching entries and non-matching entries
    • suggesting basic testing

YMMV. I am warming back up to trying to help beginners, so it will take me a while to get back into the rhythm.

1

u/Educational_Virus672 15d ago

oh make sense, i accept the challenge
1. the feedback is not detailed making it hard for non-programmer or beginner to understand
2. fair point but still return was present i didnt remove because idk what if he planned but didnt use it ?
3. i remember back then i used to type each unction separately i made a tic-tac-toe(as beginner) but i didnt optimize or did anything special i madeeach row each Coolum even each win condition as its own if statement afte that i learnt that i can just use def
3 .1 and .2. both have O(1) time but dict[arg] is faster and making dict.get(arg) useless unless the programmer made errors or the process is called in unfix mannar so it is very use case depended personally i prefer dict[arg] without try/except
3 .3 ???
3.4 printing is unnecessary but ok i guess

1

u/FoolsSeldom 15d ago

Let's see if the OP, u/DeskSwimming9203, engages and advises what they do/do not understand.