1. make a list called groceries with the values "banana", "orange", and "apple". Define these two defaultdictionaries:
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
2. Define a function compute_bill
that takes one argument food as input. In the function, create a variable total
with an initial value of zero. For each item in the food list, add the price of that item to the total. Finally, return the total. Ignore whether or not the item you're billing for is in stock. Note that your function should work for any food list.
3. Make the following changes to your compute_bill
function:
While you loop through each item of food, only add the price of the item to the total if the item's stock count is greater than zero.
If the item is in stock and after you add the price to the total, subtract one from the item's stock count.
groceries=["banana", "orange", "apple"]
stock={
"banana" : 6,
"apple" : 0,
"orange" : 32,
"pear" : 15
}
prices={
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3
}
groceries = ["banana","apple","orange"]
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
print
for item in food:
if stock[item] > 0:
total += prices[item]
stock[item] -= 1
return total
print(compute_bill(groceries))
I wrote it like this, but I don't know if I did it right.
list function python
From the perspective, it seems to be well-made to meet the requirements of number 3.
If you want to check it yourself, you can print out the stock or check the contents of each variable while running in debug mode.
© 2025 OneMinuteCode. All rights reserved.