The code doesn't run


#1

I've typed the following but the code gives an error. I don't know if should've used for instead of elif.
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 food=="banana":
total=prices["banana"]
elif food=="orange":
total=prices["orange"]
elif food=="apple":
total=prices["apple"]
return total
Please help, I've been stuck at this point since many days.


#2

Your function shouldn't need to know the names of any food items and it should process each food item one at a time.

I should for example be able to use your function this way:

prices['bacon'] = 8
stock['bacon'] = 5
my_bill = compute_bill(['bacon', 'bacon', 'bacon', 'bacon', 'bacon', 'bacon', 'bacon'])

You can't predict in advance what food I might use, your code has to handle any amount and any food type.


#3

So, is there any other way to do it???


#4

A for loop

https://wiki.python.org/moin/ForLoop


#5

This worked !


#6

Thanks man for the help. Yes it did work


#7

This code is correct but don't forget that you could use

total += prices[f]
instead of:
total = total + prices[f]

In this case it doesn't make world of a difference but in real world programming you should use the first form. Less signs equals less bytes, less bytes equals faster compilation.