Concerning Dictionaries and += in Python 2.x

MRAB python at mrabarnett.plus.com
Tue Jan 20 01:27:53 CET 2015


On 2015-01-20 00:12, Luke Tomaneng wrote:
> I have been having a bit of trouble with the things mentioned in the title. I have written the following script for a Codecademy course:
> 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
>      for item in food:
>          if stock[item] > 0:
>              total += prices[item]
>              stock[item] = stock[item] - 1
>              return total
> Whenever I run this script, "4" is returned. It does not seem to matter what in in the list the script is run on. I have tried this on the Codecademy interpreter/emulator (I'm not sure which they use) and the repl.it interpreter, but for the same result. If anyone could find the glitch in my code, please let me know. Thanks!
>
Work through it a step at a time.

You haven't said what 'food' is when 'compute_bill is called, but I'm
guessing that the first item it checks is "banana".

stock["banana"] == 6, so it adds prices["banana"] to total, subtracts 1
from stock["banana"], and then returns the total, 4, because that's
what you've told it to do.




More information about the Python-list mailing list