Using Mathematica » Basics

Loops and Scoping

For most simple tasks (i.e. most computations a chemist has to perform), making a notebook with a bunch of input and output cells is sufficient and possibly even best.

However, sometimes the task at hand is not so simple and so we'll need to progress to more complex structures.

Table and Do

Both Table and Do list over a range or a set of inputs and apply a function.

For example we can iterate over the numbers going from 1 to 10

 Table[i*i, {i,10}]

Or over an arbitrary list of inputs

 Table[i*i, {i, {a, b, c, d, e}}]

The difference is that Table returns a List while Do returns either Null or anything returned from Return

Usually this means one wants to use Table , however this behavior gives Do two distinct advantages. The first is that Table must return something at every step, while Do used in conjunction with Reap and Sow need not. For example let's get the prime numbers between 1 and 1000 :


Table would return Null every time there wasn't a prime meaning we'd have vastly too many outputs.

Secondly and most critically, Do can go over an infinite range, when used with Break or Return which acts like a ``````While[True, body] loop, but cleaner. In general, Do can be used in this way whenever While would have been used. For example:

 Do[If[RandomReal[]<.00001, Return[i]], {i,∞}]

This simulates the following loop:


But Do is a cleaner construct, owing to its automatic scoping of the i and implicit incrementor

Module, With, and Block

Module , With , and Block are called scoping constructs. That is, they let you use a variable or multiple variables without having to change or set them globally, or. This is easiest to show in an example:

Consider the following chunk of code:


Then check the current value of a


Now try checking a in a Module where the variable a has been scoped


Notice that the value of a is not its global value. This is because Module creates its own scope to execute the code in.

This is the basic use of a scoping construct, protecting code from being influenced by the global state.

Each construct has its own peculiarities, but these will be discussed more later. For now, we'll only discuss Module as its usage is the clearest.


Module has the following form:


where var1,var2,...,varn are either simple variable names or variable names with initial values.

Past that, one can write code with Module just as one would normally.

Consider the following:


The code executes just as one would expect, the only difference being that v1 has been renamed. If one runs the following it becomes clear how Module works:

  {v1, v2=10, v3=50, v4},

All module does is replace each variable in the first argument with the variable name followed by $i where i is an integer (given by the value of the global variable $ModuleNumber when the Module is executed).