12. Stocking Out


#1

I've spent a long time trying to debug this code but can never get the right version!

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 item in food :
if stock [ item ] > 0 :
total += prices [ item ]
stock [ item ] -= 1
return total

Oops, try again. calling compute_bill with a list containing 1 apple, 1 pear and 1 banana resulted in 4 instead of the correct 7

Thanks for the help :smile:


#2

Try replacing item with key in your brackets, and eliminate the spaces between your list title and the brackets. White space matters in Python.


#3

Hi @arcplayer37090 ,

Because the code that you posted is not formatted, it is difficult for other users to read and debug it. After code has been pasted into the editing window for posting, you can format it by selecting it, and then by clicking the </> button above the editing area. Alternatively, you can place three backquotes on the line before the code and three backquotes on the line after the code. This will enable us to see important details, such as the indentation and underscores. If you use the backquotes, your code will be color-coded, making it especially easy to read.

Make sure that your return statement is indented by the correct amount, so that it is not part of the for loop.