Switch

Switch[expr, form1, value1, form2, value2, ...]
evaluates expr, then compares it with each of the in turn, evaluating and returning the corresponding to the first match found.

DetailsDetails

  • Only the corresponding to the first that matches expr is evaluated. Each is evaluated only when the match is tried.
  • If the last is the pattern , then the corresponding is always returned if this case is reached.
  • If none of the match expr, the Switch is returned unevaluated.
  • Switch has attribute HoldRest.
  • You can use Break, Return, and Throw in Switch.

ExamplesExamplesopen allclose all

Basic Examples (2)Basic Examples (2)

Process Boolean value to 1 or 0, giving a message and defaulting to 0 when not Boolean:

In[1]:=
Click for copyable input
In[2]:=
Click for copyable input
In[3]:=
Click for copyable input
Out[3]=

Give a suggested symbolic transformation for an expression:

In[1]:=
Click for copyable input
In[2]:=
Click for copyable input
Out[2]=

Try the transformation:

In[3]:=
Click for copyable input
Out[3]=
New in 1
New to Mathematica? Find your learning path »
Have a question? Ask support »