Creating a shopping list code

Asked 2 years ago, Updated 2 years ago, 55 views

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

2022-09-20 16:31

1 Answers

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.


2022-09-20 16:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.