Variables and Expressions
A variable is a name for a quantity.
An expression is a recipe that uses quantities to produce another quantity.
That is the useful distinction:
variable: a name
expression: a computation
Variables Name Values
In
the symbol names the value 3.
The letter is not special. It is a handle. We use the handle because the value may appear in many places.
In ML, a variable may name:
- a scalar such as a loss
- a vector such as an embedding
- a matrix such as a weight table
- a probability
- a model parameter
The principle is the same: the symbol lets us refer to a quantity without rewriting the quantity every time.
In the statement , what value does name?
Compute it first, then check your number.
HintRead the equals sign
Here the equals sign tells you what value the name refers to.
SolutionNamed value
The variable names the value 7. Here is a handle for a known
quantity, not a mystery to solve.
Expressions Compute Values
This is an expression:
It is a recipe:
take x
multiply by 2
add 1
If , then:
If , then:
Same expression. Different input. Different result.
If , what is ?
Compute it first, then check your number.
HintSubstitute first
Replace with 5, then follow the order of operations.
SolutionSubstitution
Substitute :
This is the expression-as-recipe idea: replace the variable with its value, then follow the operations in order.
Constants and Variables
In
the values 2 and 1 are constants. Their values are fixed inside this
expression.
The value of can change.
This is why expressions are useful. One expression can describe many related computations.
In , enter 1 if is the part whose value can change.
Compute it first, then check your number.
HintCompare the symbols
Which symbol can be replaced by different input values?
SolutionReasoning
Enter 1. In this expression, is the variable. The numbers 2 and
1 are constants.
Code Mirror
The expression:
can be mirrored in code:
x = 3
value = 2 * x + 1
print(value)
The code and the expression are doing the same work. The code makes each step explicit. The expression writes the computation compactly.
What does this code print?
x = 4
value = 2 * x + 1
print(value)
Compute it first, then check your number.
HintMirror the expression
This code evaluates with .
SolutionTrace
The variable is assigned 4.
Then:
So the code prints 9. The code line value = 2 * x + 1 is the same
computation as the expression with .
Common Doubt
Does a variable always stand for an unknown value?
No. Sometimes a variable is unknown. Sometimes it is known but named for convenience. In ML code, variables often name known arrays or tensors. The point is not mystery. The point is reference.
Next, we give expressions a name and treat them as functions.