# Stocking Out

#1

My code is correct ,but i dont get why we have to decrease 1 of the stock ! when u write that
'' for item in food: if stock[item] > 0: total = total + prices[item]'' that item in prices[item] is not just the items bigger than 0 ??

``````shopping_list = ["banana", "orange", "apple"]

stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}

prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}

def compute_bill(food):
total = 0
for item in food:
if stock[item] > 0:
total = total + prices[item]
stock[item] = stock[item] - 1``````

Error in computing bill( Oops, try again. calling compute_bill with a list containing 1 apple, 1 pear and 1 banana resulted in None instead of the correct 7)
Stock[item]=stock[item]-1
#2

why we have to decrease 1 from the stock !
Every time you buy one thing (fruit) it will get reduced by 1 (in number).

`if stock[item] > 0:`
This line checks if a fruit is in stock or not.
If it 0,then the price will be not added !

okay lets break the last part!

``````def compute_bill(food):
total = 0
for item in food:
if stock[item] > 0:
total = total + prices[item]
stock[item] = stock[item] - 1``````

Analysis of this code....

1.We define a function `compute_bill(food)` that takes a list i.e `food`.
2.We define a local variable `total` and set it to 0, it will keep track of our total amount.
3.We loop through this `food` list.
4.If this item of food list (fruits) is in stock (greater than 0 in numbers)
5. Then we add price of fruit to total.
6. As we buy fruits from stock, the number of fruits will be get decreased by 1.
(As we're buying one item of every fruit so we will subtract 1 every time we buy(when looping) fruit )

Visualization of this code: http://www.pythontutor.com
Put your full code there and visualize the whole process!

#3

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