python - Decreasing value in dictionary -
i learning python , have simple problem program. have 2 dictionaries keys string , values connected them. lets it's shop fruits , prices.
shopping_list = ["banana", "orange", "apple"] stock = { "banana": 6, "apple": 0, "orange": 32, "pear": 15 } prices = { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 } # function calculate bill def compute_bill(food): total = 0 number in food: if (stock[number]>0): total += prices[number] stock[number] -= 1 return total print compute_bill(shopping_list)
if fruit in stock add price bill , reduce amount in stock. if not, don't anything.
error message:
calling compute_bill list containing 1 apple, 1 pear , 1 banana resulted in 0 instead of correct 7
i don't know why code not working properly.
there 2 things wrong here:
- you return immediately after testing first item, ignoring rest of items.
return
exits function, moment python executes it. - you decrement stock in wrong place, outside of loop.
both need correcting:
def compute_bill(food): total = 0 item in food: if stock[item] > 0: # item in stock. add price total, # , reduce stock one. total += prices[item] stock[item] -= 1 # loop done, return total sum of items # in stock. return total
now, instead of returning total
first item test, test items. , whenever have found item in stock, add price 1 item total, , reduce stock item 1.
one final detail, code academy tester calls compute_bill()
function for you. don't call in code, otherwise test fails have changed stock begin with. remove print compute_fill(shopping_list)
line.
Comments
Post a Comment