Lists and loops
By the end of this step you can keep many values together and do something with each one: the move that makes programs worth writing.
Lists: many values, in order
One variable holds one value. A list holds many, in order, inside square brackets:
| Python | JavaScript | |
|---|---|---|
| A list | sizes = ["S", "M", "L"] | const sizes = ["S", "M", "L"]; |
| The first item | sizes[0] | sizes[0] |
| How many items | len(sizes) | sizes.length |
Counting starts at 0, not 1. sizes[0] is "S", sizes[1] is "M". Every developer trips on this at first.
Records: named values together
A product has several facts: a name, a price, a stock count. A record keeps them together, each with a name, inside curly braces. Python calls it a dictionary; JavaScript calls it an object.
| Python | JavaScript | |
|---|---|---|
| A record | tent = {"name": "Trail Tent", "price": 249.99} | const tent = { name: "Trail Tent", price: 249.99 }; |
| Read one field | tent["price"] | tent.price |
A list of records is how most business data looks: a spreadsheet, really. Each record is a row; each field is a column.
Loops: do it for every item
A loop repeats some lines once for each item in a list.
Output
Press Run (or Ctrl+Enter) to see the output here.
Read it as: for each size in this list, print "We stock size" and the size. The indented line is the body of the loop: it runs once per item. In Python the indent (4 spaces) is what marks the body, so it matters. JavaScript uses { } instead, and the indent is just for readability.
Try it
This puts it together: lists, records, a loop, and a running total.
Output
Press Run (or Ctrl+Enter) to see the output here.
Output
Press Run (or Ctrl+Enter) to see the output here.
Look closely at the total. It starts at 0. Each time round the loop, total = total + item["price"] takes the old total, adds this item's price, and stores the result back in the box. After the last item, the box holds the sum. That pattern (start empty, add as you go) is everywhere.
Your turn
Add a fourth product to the list (a name and a price you choose), run it, and check the total went up by exactly that price.