[Tutor] Help with loops

Alan Gauld alan.gauld at yahoo.co.uk
Mon Apr 30 14:42:42 EDT 2018


On 30/04/18 14:35, Shannon Evans via Tutor wrote:
> Hi, is there any way that i can add a loop or iteration or something so
> that i dont have to write out every person who has fruit. 

Yes that's what loops are for.
You have two options in Python: a 'for' loop or a 'while' loop

In your case I suspect a 'for' loop is most appropriate.

This information
> is coming from the following json files:
> *queue.json* file
> 
> [
> 
>   ["James Bruce", "Bananas"],
> 
...
> ]
> 
> 
> 
> *stock.json* file
> 
> {
> 
> "Apples": 14,
> 
> "Bananas": 14,
> 
> "Pineapples": 0,
> 
> "Pears": 8
> 
> }

> import json
> 
> #Load the stock and queue files
> queue=json.load(open("queue.json"))
> stock=json.load(open("stock.json"))
> 

You need to start the loop here then indent everything
below. The syntax is like

for data in queue:
    name, product = data

Now change the queue access items to use name and product.

> if (stock[queue[1][1]]>0):
>     #in stock
>     print "Gave Bananas to "+ queue[1][0]
> else:
>     print "Could not give Bananas to "+ queue[1][0]
> 
> if (stock[queue[2][1]]>0):
>     #in stock
>     print "Gave Pears to "+ queue[2][0]
> else:
>     print "Could not give Pears to "+ queue[2][0]
> 
> if (stock[queue[3][1]]>0):
>     #in stock
>     print "Gave Pineapples to "+ queue[3][0]
> else:
>     print "Could not give Pineapples to "+ queue[3][0]

Try it, if you get stuck come back and show us what you did.
You will find more about Looping in my tutorial(see below)

-- 
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