Why does it show a different total or result in the console every time I run my code? - Solution and explanation


#1

Greetings! I could see why the error throughout the exercise. Here is an example of the error and a brief explanation:

1 stock = {
2 banana: 4,
3 apple: 2,
4 pear: 5
5 }
6
7 prices = {
8 banana: 10.5,
9 apple: 15.25,
10 pear: 14
11 }
12
13 def compute_bill(food):
14 total = 0
15 for item in food:
16 if stock[item] > 0:
17 total += prices[item]
18 stock[item] - 1
19 return total

You can believe that there is no error if the code matches the previously typed. However, even running your code will throw an error in the console output giving them a total variant.

The solution is simple (and I will explain why):

18 stock [item] - = 1 or stock [item] = stock [item] - 1

If you type only “stock [item] - 1” you are only indicating that you have to go back one element of the dictionary instead of subtracting 1 from the quantity of the element (stock), so it throws an error in which there is no way to get out of the loop.

I hope that I could have been of help (sorry for my English but it is not my native language).

PD: If I’m wrong, please, notify me. Thank you!


#2

the why explanation:

Is not accurate.

lets break it down.

dictionaries consist of key value pairs. You can’t go back one element in a dictionary.

lets visualize it:

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

as you can see, you do temporary subtract one from the stock, but you never update the dictionary, so the subtraction doesn’t persist. (because you do nothing with the result of the subtraction)

this also shows the loops does finish, we get 5.5 (for buying a banana and orange, apple isn’t in stock). The loop just loops through food, regardless if you update the dictionary or not


#3

Thank you for your response, effectively, it is as you say.


#4

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