If

If

If[ cond ] ... Else ... End checks a condition and executes a script block based on the result.

Usages

If[ cond ] ... End

Executes the script between If and End, unless cond is False. The block always ends with End.

Example in out
x == 4 is False, so r is not defined. x := 3
If[x == 4]
  r := 1
End
x = 3

If[ cond ] ... Else ... End

Executes the script after If if cond is not False, and the script after Else otherwise.

Example in out
x == 4 is False, so the Else block is executed. x := 3
If[x == 4]
  r := 1
Else
  r := 0
End
r = 0
Test whether a number is even. x := 6
If[Mod[x, 2] == 0]
  r := 'even'
Else
  r := 'odd'
End
r = 'even'
Choose a text based on a random value. a := RandomInt[{-5, 5}, Exclude=>0]
If[a < 0]
  s := Text[`negative`]
Else
  s := Text[`positive`]
End
for example a = 3
s = Text[`positive`]

If[ cond1 ] ... ElseIf[ cond2 ] ... Else ... End

The conditions are checked in order. The block of the first condition that is not False is executed, and the rest is skipped. If all conditions are False, the Else block is executed. Any number of ElseIf blocks is allowed, and Else is optional.

Example in out
The second condition holds. x := 2
If[x == 4]
  r := 1
ElseIf[x == 2]
  r := 2
Else
  r := 0
End
r = 2
Only the first condition that holds counts. x := 7
If[x < 3]
  r := 1
ElseIf[x < 5]
  r := 2
ElseIf[x < 10]
  r := 3
Else
  r := 0
End
r = 3
Details
  • Conditions can be comparisons with ==, <, <=, >, >= and <>, type checks such as Type[x] == NaturalNumber, and combinations with AND, OR and Not. In a condition, < and the other relations are evaluated, unlike elsewhere in a script.
Example in out
AND: both conditions must hold. x := 5
If[x > 2 AND x < 10]
  r := 1
Else
  r := 0
End
r = 1
OR: one of the conditions must hold. x := 5
If[x < 2 OR x > 4]
  r := 1
Else
  r := 0
End
r = 1
Not reverses the condition. x := 5
If[Not[x == 5]]
  r := 1
Else
  r := 0
End
r = 0
Warning

Only a condition that is False skips the block. A condition that cannot be decided, such as y == 4 when y has no value, is treated as True, and so is a value that is not a condition at all, such as If[5]. Use Strict to treat an undecided condition as False: If[Strict[y == 4]].

Example in out
y has no value, so the condition is undecided and the first block is executed. If[y == 4]
  r := 1
Else
  r := 0
End
r = 1

See also: Strict, While, For, EqualsEval, Type