Skip to content
AgileLogics
6 min read

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 = value stores 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] removes x's value.
  • Results are written in a standard order, so x^2 + 1 comes back as 1 + x^2.
  • /. x -> 3 substitutes a value just for this expression (rules are covered in Level 2).

= versus :=

  • a = rhs (Set) evaluates rhs now and stores the result.
  • a := rhs (SetDelayed) stores rhs unevaluated and evaluates it each time a is 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_price means something else entirely (a pattern — see "Defining Functions"). Use camelCase.

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 = 5 earlier in the session, x^2 + 1 gives 26, not a formula. Use Clear[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