WolframLang: If Then Else (Conditional)

By Xah Lee. Date: . Last updated: .
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, t, f, alt]
  • If test eval to neither True nor False, eval alt and return it.
If[x > y, "yes", "no", 3] === 3

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,

🛑 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"]

(* 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 *)
(* "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.

WolframLang, conditional

WolframLang Boolean