11/13 code wrong?!


#1

This is my code:

shopping_list = ["banana", "orange", "apple"]

stock = {
    "banana": 6,
    "apple": 0,
    "orange": 32,
    "pear": 15
}
    
prices = {
    "banana": 4,
    "apple": 2,
    "orange": 1.5,
    "pear": 3
}

def compute_bill(food):
    total = 0
for key in food:
    total += prices[key]
return total

The console window:

  File "python", line 21
SyntaxError: 'return' outside function

And if I delete “return total” it gives me:

Traceback (most recent call last):
  File "python", line 19, in <module>
NameError: name 'food' is not defined

???!??!?!??!???!?!!!???!??!?!


#2

This means there is an indentation issue. The return statement needs to be inside the function block. I’m going to format your post so we can take a closer look. At this point we know one thing to look for.

Edit:

As suspected. Both the for statement and the return are outside of the function. We need to correct the indentation so that they are seen by the compiler as part of the block.

def compute_bill(food):
    total = 0
    for key in food:
        total += prices[key]
    return total

Hint: A block starts with a colon and the next line gets four spaces added to the beginning. Notice above how the for block is indented by eight spaces? That’s what is needed to keep it four spaces in from where for is written.

return is just inside the function block, and not the for, so it gets only four spaces. Should it accidentally slip inside the for block, the program will not run correctly.