Variables and Assignment
Prerequisites: Numbers: exact and approximate
Assigning values
price = 20;
qty = 3;
price qty
qty = qty + 1;
qty += 2;
qty
60
6
name = valuestores a value.+=,-=,*=,++, and--also work.- Once assigned, the symbol is replaced by its value everywhere.
Symbols without values
A symbol with no value stays as itself — that's what makes symbolic math possible:
Clear[x]
x^2 + 1
(x + 1)^2 /. x -> 3
1 + x^2
16
Clear[x]removesx's value.- Results are written in a standard order, so
x^2 + 1comes back as1 + x^2. /. x -> 3substitutes a value just for this expression (rules are covered in Level 2).
= versus :=
a = rhs(Set) evaluatesrhsnow and stores the result.a := rhs(SetDelayed) storesrhsunevaluated and evaluates it each timeais used.
a = 1;
b = a + 1;
c := a + 1;
a = 10;
{b, c}
{2, 11}
b was computed when a was 1; c is recomputed with the current a.
You'll use := mostly for defining functions.
Several at once
{p, q} = {1, 2};
{p, q} = {q, p};
{p, q}
{2, 1}
Naming rules
- Names are case-sensitive and may contain letters and digits:
total,total2,unitPrice. - Start your own names with a lowercase letter, so they never clash with built-in functions, which all start with a capital.
- No underscores:
unit_pricemeans something else entirely (a pattern — see "Defining Functions"). UsecamelCase.
Built-in symbols are protected:
Pi = 3
Set::wrsym: Symbol Pi is Protected.
3
The message explains the problem, and Pi keeps its value.
Common mistakes
- Forgetting a variable already has a value. If
x = 5earlier in the session,x^2 + 1gives26, not a formula. UseClear[x]— or quit the kernel (Evaluation → Quit Kernel) for a fresh start.
Practice
Store a width of 4 and a height of 7, compute the area, then change the
width to 5 and show that a delayed area := ... updates automatically.
Show solution
width = 4;
height = 7;
area := width height;
area
width = 5;
area
28
35