11/13 Making A Purchase


#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/courses/learn-python/lessons/a-day-at-the-supermarket/exercises/making-a-purchase?link_content_target=interstitial_lesson

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?

```python

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>

#2

The question has removed indenting in code
image


#3

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.


#4

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.


#5

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


#6

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

#7

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.


#8

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