A name for a value
Give a value a name, then use the name in a calculation. About 7 minutes.
A box with a label
A variable is a box with a label on it. Picture a shelf in a shop: the label says "price" and inside the box sits a number. In code you make the box once, give it a name and put a value inside.
After that, you can use the name whenever you want the value. The code on these pages is written in a Python style. Your editor shows the language you chose, and the idea is exactly the same in all of them.
price = 12 quantity = 3
Using the names
Once a value has a name, you can use the name inside a calculation, just like you would use the number itself. The computer looks inside the box and takes the value out.
You can also keep the answer in a new box, so the next line can use it too. Code runs from the top to the bottom, like a recipe: each line happens after the one above it.
price = 12 quantity = 3 total = price * quantity
- price
- 12
The first line makes a box named price and puts 12 inside.
Names that explain
You could call every box x, y and z, and the computer would not mind. But a person reading the code later would have to guess what is inside. A name like total or price tells them straight away.
Pick names that say what the value means. Use lowercase words, and join two words with an underscore if you need to.
price is 5 and quantity is 4. After total = price * quantity, what is inside total?
- A20
- B9
- C54
Show the answer
20. The star means multiply: 5 times 4 is 20.
Shop bill
A shop sells an item at a price each. You buy a few of them and pay one flat delivery fee on top. Return the total bill.
price = 12, quantity = 3, delivery = 5 → 41
0 ≤ price, quantity, delivery ≤ 1,000