Making purchase fully stuck


#1



Replace this line with your code.


#2

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
   
   
   total+=food[key]
   return total

#3

lets add a function call:

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

print compute_bill(shopping_list)

so food (the function parameter) contains a list of products the customer wants to buy, so we need to loop over food to get each item the customer wants to buy, and add the price of this item to total


#4

sir it is saying global name key is not defined


#5

Traceback (most recent call last):
File "python", line 25, in
File "python", line 22, in compute_bill
NameError: global name 'key' is not defined


#6

because it isn't? You can use key as iterator. See my explanation about why you need a loop


#7

sir please give me the link


#8

The link of what?


#9

sir link of your explanation of this problem


#10

its in this topic? It explains why you need to a loop, and what food is

If you need more help, post an updated version of your code


#11

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

#12

sir still type error


#13

here:

total+=food[key]

food is a list, and key is a string (for example apple), lists can't only accessed by indexes. You need to add the price of product to total, use key as key to get the price of a product from the prices dictionary

finally, move return outside the loop. A function ends the moment a return keyword is reached. So currently your function ends the fist run/iteration of the loop.


#14

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

"""sir it is returning 4 instead of 10.5"""


#15

here:

total+=food[key]

explain to me why you use food, so i can see where you thought process goes wrong

i covered that:


#16

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