[Tutor] updating stock list
Alan Gauld
alan.gauld at yahoo.co.uk
Mon Apr 30 19:51:13 EDT 2018
On 30/04/18 23:15, Shannon Evans via Tutor wrote:
> Hi, i'm wanting to update the stock list at the end so that the fruit
> that's given is taken subtracted from the original stock list. The code
> i've written isn't updating it it's just staying the same. Any idea what i
> can do to fix this?
>
>
> import json
>
> stock_json= json.load(open("stock.json"))
> queue_json= json.load(open("queue.json"))
>
> queue=[
> ["James Bruce", "Bananas"],
> ["Katherine Newton", "Bananas"],
...
> ]
>
> stock={
> "Apples": 14,
> "Bananas": 14,
> "Pineapples": 0,
> "Pears": 8
> }
>
> for i in queue:
This should work OK but by convention programmers use single
letter names like i to indicate indeces or other temporary
integers or characters. It might be better to use a more
descriptive name than i for your data.
> if stock[i[1]]>0:
> print("Gave {} to {}".format(i[1],i[0]))
> else:
> print("Could not give {} to {}".format(i[1],i[0]))
But the loop should work and display the appropriate messages.
> def total_stock(fruit):
> total=0
> for i in fruit:
> if stock[i]>0:
> stock[i]=stock[i]-1
> return total
Notice that this defines a function but...
> print stock
You never call it. Instead you print stock which
is just your original list. Oncwe you have defined
the function you need to explicitly call it for it
to do anything.
Notice too that in your function you use i as a
key into stock. That implies that fruit is a
list of strings(ie names of fruit) - is that
going to be true? Or will it be the pairs
from the queue data?In which case you need
to extract the fruit name.
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list