Context is an advanced topic which need not be studied by
the novice until writing complex packages which might have conflicting
names. However, both Modules and Packages would be commonly used to
define functions and procedures to be used in various application
while avoiding conflict between so called "local" and "global"
variables.
A context in Mathematica is like an internal path. A
variable defined in a context other than the current context (given
by the value of $Context) is inaccessible unless explicitly
referenced with its full context name. If the context in which it
has been defined has been added to the system environment via the
$ContextPath (usually by a BeginPackage[] statement),
then Mathematica will find it by prepending successive context
names from $ContextPath to the variable name until a match is
found. If the context in which it has been defined has not been
added to ContextPath, then Mathematica will not acknowledge
its existence unless given the full context name. The
following session should make this easier to see:
Example session changing contexts
In[1]:= $Context (* where Mathematica starts *)
Out[1]= Global`
In[2]:= $ContextPath (* beginning search path *)
Out[2]= {Global`, System`}
In[3]:= n = 6! (* give value to variable Global`n *)
Out[3]= 720
In[4]:= BeginPackage["Nothing`"] (* change $Context & $ContextPath *)
Out[4]= Nothing`
In[5]:= $ContextPath (* verify search path no longer includes Global` *)
Out[5]= {Nothing`, System`}
In[6]:= mean::usage = "mean[List] returns mean of List" (* in search path *)
Out[6]= mean[List] returns mean of List
In[7]:= Begin["`private`"] (* changes only $Context *)
Out[7]= Nothing`private`
In[8]:= $ContextPath (* verify search path is the same *)
Out[8]= {Nothing`, System`}
In[9]:= n = 0 (* this is Nothing`private`n, a different variable *)
Out[9]= 0
In[10]:= mean[s_List]:= Apply[Plus,s]/Length[s] /; Length[s] > 0
In[11]:= End[] (* return to previous $Context *)
Out[11]= Nothing`private`
In[12]:= EndPackage[] (* return to original $Context *)
In[13]:= $ContextPath (* verify $ContextPath has permanently changed *)
Out[13]= {Nothing`, Global`, System`}
In[14]:= n (* verify value of Global`n *)
Out[14]= 720
In[15]:= Nothing`private`n (* verify value of "hidden" variable *)
Out[15]= 0
In[16]:= x = Range[10] (* create list from 1 to 10 *)
Out[16]= {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
In[17]:= mean[x] (* find the mean of the list *)
11
Out[17]= --
2
$Context
$ContextPath
n equal six factorial
BeginPackage statement
$ContextPath again (note changes)
Nothing`mean with usage statement
$Context but not $ContextPath with Begin
Nothing`private`n equal zero
Nothing`mean find the average of a list
Nothing package environment
Nothing variables
Global`n is set to
n
x equal the list
1, 2, ..., 10x