What the signs do, and the one that does two jobs
Show on a big screenThree notebooks, two pens, one eraser. What is the bill?
Loading lab…
- Start: bill = 0.
- Line 1: notebook × 3. bill = 135.
- Line 2: + pen × 2. bill = 159.
- Line 3: + eraser. bill = 163.
+now joins text and 163. Total: 163 rupees.
The bill is 163 rupees. At the school counter, a notebook costs 45 rupees. A pen costs 12 rupees and an eraser 4.
So the bill is 3 × 45 + 2 × 12 + 4. That is 135 + 24 + 4 = 163.
A sign is a symbol, such as +, that works on values.
The rule
The signs do arithmetic on two numbers. + joins instead when one side is text. The other side must be something that can be written out. A nothing cannot be written out. In this editor, text plus nothing stops the run.
Numbers, text and true or false can be written out.
| Sign | Does | A line | Runs to |
|---|---|---|---|
+ | Adds | 45 + 12 | 57 |
- | Subtracts | 45 - 12 | 33 |
* | Multiplies | 45 * 3 | 135 |
/ | Divides | 12 / 4 | 3 |
% | Leftover | 13 % 5 | 3 |
% gives what is left after dividing. Here 13 % 5 is 3: 13 is 2 fives plus 3 left over.
Multiply and divide happen before add and subtract. So 45 * 3 + 12 gives 147. First 45 * 3 is 135. Then 135 + 12 is 147.
print("Total: " + bill + " rupees"); prints Total: 163 rupees. The same sign + is joining here, not adding. It joins from left to right.
Suppose the counter had no chalk. Then the box chalk holds nothing. In this editor, joining text to chalk stops the run:
You cannot do a text + nothing. Check the values on this line.
Try "4" for the eraser. Then 159 and "4" join as text. The total is 1594, not 163.
Try the lab to finish this lesson.