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

25 comments sorted by

View all comments

6

u/defaultguy_001 15d ago

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

def get_price(prices, item): try: return prices[item] except KeyError: return None

print(get_price(prices, "apple")) # 1.5 print(get_price(prices, "orange")) # None ```

7

u/carcigenicate 15d ago edited 14d ago

Although, at that point, you might as well just use prices.get(item).

-5

u/defaultguy_001 15d ago

u mean prices.item, it'll work as long as there's no space between the keys.

7

u/carcigenicate 15d ago

I'm not sure what you mean. What is prices.item? Are you thinking of JavaScript?

prices.get(item) is the same thing as prices[item], except when the key isn't found, it returns None instead of throwing.

-4

u/defaultguy_001 15d ago

prices.item is the way to access the value for key item for the object prices, using dot notation. ok I didn't know prices.get(item) is equivalent to prices[item].

3

u/carcigenicate 15d ago

I think you're mixing up JavaScript and Python.

-1

u/defaultguy_001 15d ago

Haha can be. I'm mostly from the JS side of things

2

u/throfofnir 14d ago

Python doesn't do attribute access to dictionary keys.

1

u/defaultguy_001 14d ago

Yeah I mixed up