11/13 Making A Purchase



<Below this line, add a link to the EXACT exercise that you are stuck at.>

No matter what I put in place of ‘item’ (x, n, etc), I get the following error:

compute_bill([‘apple’]) resulted in a NameError: global name ‘item’ is not defined.

What can I call the items on the shopping list that the code will recognise?


shopping_list = [“banana”, “orange”, “apple”]

stock = {
“banana”: 6,
“apple”: 0,
“orange”: 32,
“pear”: 15

prices = {
“banana”: 4,
“apple”: 2,
“orange”: 1.5,
“pear”: 3

Write your code below!

def compute_bill(food):
total = 0
if item in food:
total =+ prices[item]
return total

<do not remove the three backticks above>


The question has removed indenting in code


Item is not defined in the function, so Python looks for it in global scope, where it is also undefined.

Use for instead of if.


Thank you! I don’t know why I was using ‘if’ facepalm
It already understands the function better and has stopped the first error. It’s now giving a new error that the total is incorrect. At least I can now look that one up in the forums.


Remove the indentation from your return line so it is not inside the loop.


It’s strange, it clearly changes things but still doesn’t make the function return the correct number. If I have return directly under ‘total’ in the previous line, it returns 4 (supposed to return 10.5). If I back the indent up by 2 so that return is in line with the ‘for’, it returns 3. If I back it up a further 2 (all the way), then there is an error that my return is outside of the function.

EDIT I have finally got it working! I had written =+ instead of +=, thinking that =+ made more logical sense (total equals that addition of item prices) but obviously not! Thank you for your help mtf, and for anyone looking for the answer, it is:

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


In compound operations, the operation on the left is first to complete, followed by the operation on the right (the assignment). A temporary object is created for the operation to take place, then the result assigned back onto the variable. The = is always last.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.