Basic

An expression makes one value

An expression is a recipe that boils down to a single value. The computer works the inside out, and the order it uses is fixed. Reading expressions is the skill that lets you follow any computation without running it.

What you will see

5.0

About 2 min of reading

Try It

Work an expression on paper, then check it.

1

A plain sum. Addition and subtraction run left to right.

print(1 + 2 - 3)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
0
2

The multiply runs before the add, so this is 14 not 20.

print(2 + 3 * 4)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
14
3

Brackets force the add first, giving 20.

print((2 + 3) * 4)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
20
4

Division always gives a decimal number, even when it divides evenly.

print(10 / 2)

Before you run it, say out loud what it will print. Then open the answer.

What it prints
5.0
The single slash gives a decimal result. A double slash gives a whole number and throws away any remainder, which is the tool for counting whole groups.

Data Flow

The computer finds the tightest piece of the recipe, works it out, and repeats until one value is left.
1 3 * 4 makes 12
↓
2 2 + 12 makes 14
↓
3 print shows the one value
↓
4 The screen shows 14
Line by line

Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.

print(1 + 2 - 3) 0
Why this works
The fixed order

Multiply, divide and remainder run before add and subtract, because they bind tighter. That order is a rule every language shares, so you never have to guess it, only remember it. When the default order is not what you want, brackets state it.

Reading without running

To follow an expression, find the tightest piece, work it out, and write the answer back. Repeat until one value is left. That is exactly what the computer does, and practising it on paper is how you predict a program instead of waiting for it.

Examples

Boil it down

print(2 + 3 * 4)

This is not 20. The multiply runs first, making 12, then the add makes 14. The whole line is a recipe for one value, and the screen shows that value.

Brackets say otherwise

print((2 + 3) * 4)

Brackets override the default order. Here the add runs first, making 5, then the multiply gives 20. Brackets are the only way to say "do this part first", and they change the answer honestly.

Names are read first

w = 3
print(2 + 3 * w)

A name is swapped for its value before anything is computed, so the recipe is 2 + 3 * 3. The order still puts the multiply first, giving 11.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Values come in kinds
Previous Lesson
Values come in kinds
Next Lesson
Text is a value you can build
Text is a value you can build →