Making a Purchase


#1

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
for item in food:
total = total + prices[item]
return total

I have no idea why this isn't working. I've seen a lot of suggestions using a += function but that hasn't been introduced in the course, as far as I know. This is really frustrating.


#2

Apparently it was the indentation of my return line. This is awful. Why am I doing this.


#3

@mattdhall,

So have you figured it out already? :slight_smile:


#4

Yes, thank you very much.


#5

Oh and one more thing: if you did the modules in sequence, you would have met += in this unit: Taking a vacation. Here is the link: https://www.codecademy.com/en/courses/python-beginner-P5YtY/1/3?curriculum_id=4f89dab3d788890003000096


#6

use "price" not "prices" and it might help.
I did like this and it worked.

price = {}
price['banana'] = 4
price['apple'] = 2
price['orange'] = 1.5
price['pear'] = 3
stock = {}
stock['banana'] = 6
stock['apple'] = 0
stock['orange']= 32
stock['pear'] = 15
for fruits in prices:
print fruits
print "price: %s" % price[fruits]
print "stock: %s" % stock[fruits]


#7

I understand everything except the prices[item] part.
Seems simple enough but I did not know I would have to use brackets for this instead of parentheses and did not expect it given the instructions and example I used as a guide.

Just needed an explanation. Thanks!!! The answer may be simple and just went over my head, I just like to understand what I am doing :slight_smile:


#8

When using a variable to reference an item stored in a list, you should use brackets. I think of it as, "The list is in brackets, so I use brackets to get into the list." Hope that helps.


#9

Hey guys, so....
the prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}

this is... a dictionary? a list? I think dictionary, correct?

how does the number '4' for "banana" get into 'prices[item]' in the function?

Write your code below!

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

compute_bill(shopping_list)

so the number 4 from 'banana' is pulled into 'prices[item]'..... because of 'for item in food' ??

And does the shopping_list argument only work because its the same fruits as in the prices and stock list?

dunno if that made sense. Thanks!


#10

Actually, that does help!!! Thank you so much!