If
If
If[ cond ] ... Else ... End checks a condition and executes a script block based on the result.
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 |
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 |
r = 0 |
| Test whether a number is even. | x := 6 |
r = 'even' |
| Choose a text based on a random value. | a := RandomInt[{-5, 5}, Exclude=>0] |
for example a = 3s = 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 |
r = 2 |
| Only the first condition that holds counts. | x := 7 |
r = 3 |
- Conditions can be comparisons with
==,<,<=,>,>=and<>, type checks such asType[x] == NaturalNumber, and combinations withAND,ORandNot. In a condition,<and the other relations are evaluated, unlike elsewhere in a script.
| Example | in | out |
|---|---|---|
AND: both conditions must hold. |
x := 5 |
r = 1 |
OR: one of the conditions must hold. |
x := 5 |
r = 1 |
Not reverses the condition. |
x := 5 |
r = 0 |
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 |
See also: Strict, While, For, EqualsEval, Type