WolframLang: If Then Else (Conditional)
If[ test, t, f]
-
- If test eval to
True
, eval t and return it. - If test eval to
False
, eval f and return it. - If neither, return the whole expression unchanged.
If[3 > 2, "yes", "no"] === "yes"
If[x > y, "yes", "no"] (* returns the whole unchanged *)
- If test eval to
If[ test, t, f, alt]
-
- If test eval to neither
True
norFalse
, eval alt and return it.
If[x > y, "yes", "no", 3] === 3
- If test eval to neither
Add Semicolon Between Multiple Expressions
Each argument of If
must be a single expression.
If you have multiple expressions, add semicolon
between them.
〔see CompoundExpression and Semicolon〕
For example:
If[3 > 1, exprA1; exprA2; exprA3 , exprB1; exprB2 ]
🛑 WARNING: Test Must Eval to Symbol True or Symbol False
if a function's argument requires True
/False
, such as the first argument of If
, the test must eval to exactly
True
or
False
, else the entire expression is returned symbolically as is.
Example:
result = If[x, "yes", "no"] result (* If[x, "yes", "no"] *) (* The symbolic expression is returned unchanged. because x is not one of the exact symbols True, False *) (* now assign a val to x *) x = 3 < 4; (* result changed *) result (* "yes" *)
💡 TIP: Casting, Coersion, Convert Type?
There is no “casting”,
no “coerce”,
no forcing or “convert” a value to be True
/False
.
Your code need to eval to
True
/False
explicitly.
- You can use
N[expr]
to convert all numbers from exact to numerical, then useEqual
(double equal==
) to test equality of numbers that are in expressions. 〔see Force Numerical Result〕 - use
SameQ
(triple equal===
) to test sameness of symbolic expressions. 〔see Equality Test〕 - Any function whose name ends in Q return either
True
orFalse
. 〔see List Functions〕