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.
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:
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:
print("Bill Total = £",BillTotal) print("Number of items purchased =",itemNumber) |
|