Custom Search

PYTHON: for......in....

This command enables the computer to take a list of items from a string in turn and use them as a variable.

In Python, lists are simply comma-separated values, within square brackets.

The 'for variable in list: block' instruction goes through the given list and successively stores each value of the list in square brackets in the variable you named after the 'for' and then executes the block.

Suppose we have items purchased by a cutomer in a shop.

 

We can set these up in a list:

purchases = [4.35, 2, 19.95, 22.70, 5]

 

Suppose we want to add up the cost of all of the purchases and call that value the billTotal

 

We can write a simple program for this:

(Remember the indentation and colons must not be omitted!)

Also remember you must declare each variable - give it an initial value.

purchases = [4.35, 2, 19.95, 22.70, 5]

billTotal=0

for purchase in purchases:

billTotal = billTotal + purchase

print("Bill Total = £",BillTotal)

 

We can count how many items were purchases.

purchases = [4.35, 2, 19.95, 22.70, 5]

billTotal=0

itemNumber=0

for purchase in purchases:

billTotal = billTotal + purchase

itemNumber=itemNumber+1

print("Bill Total = £",BillTotal)

print("Number of items purchased =",itemNumber)