Defining Variables

When you do long calculations, it is often convenient to give names to your intermediate results. Just as in standard mathematics, or in other computer languages, you can do this by introducing named variables.

This sets the value of the variable to be .
In[1]:=
Click for copyable input
Out[1]=
Whenever appears, Mathematica now replaces it with the value .
In[2]:=
Click for copyable input
Out[2]=
This assigns a new value to .
In[3]:=
Click for copyable input
Out[3]=
is set to be the numerical value of to 40-digit accuracy.
In[4]:=
Click for copyable input
Out[4]=
Here is the value you defined for .
In[5]:=
Click for copyable input
Out[5]=
This gives the numerical value of , to the same accuracy as .
In[6]:=
Click for copyable input
Out[6]=
x=valueassign a value to the variable x
x=y=valueassign a value to both x and y
x=. or Clear[x]remove any value assigned to x

Assigning values to variables.

It is very important to realize that values you assign to variables are permanent. Once you have assigned a value to a particular variable, the value will be kept until you explicitly remove it. The value will, of course, disappear if you start a whole new Mathematica session.

Forgetting about definitions you made earlier is the single most common cause of mistakes when using Mathematica. If you set , Mathematica assumes that you always want to have the value , until or unless you explicitly tell it otherwise. To avoid mistakes, you should remove values you have defined as soon as you have finished using them.

• Remove values you assign to variables as soon as you finish using them.

A useful principle in using Mathematica.

The variables you define can have almost any name. There is no limit on the length of their names. One constraint, however, is that variable names can never start with numbers. For example, could be a variable, but means .

Mathematica uses both uppercase and lowercase letters. There is a convention that built-in Mathematica objects always have names starting with uppercase (capital) letters. To avoid confusion, you should always choose names for your own variables that start with lowercase letters.

aaaaaa variable name containing only lowercase letters
Aaaaaa built-in object whose name begins with a capital letter

Naming conventions.

You can type formulas involving variables in Mathematica almost exactly as you would in mathematics. There are a few important points to watch, however.

means times .
with no space is the variable with name .
means times .
means , not .

Some points to watch when using variables in Mathematica.

New to Mathematica? Find your learning path »
Have a question? Ask support »