WolframLang: If Then Else (Conditionals, Branching)

By Xah Lee. Date: . Last updated: .
If[ test, t, f]
  • If test eval to True, eval and return t.
  • If test eval to False, eval and return f.
  • If neither, return the whole expression unchanged.
If[ test, t, f, n]
  • If test eval to neither True nor False, eval and return n.

If

example:

If[3 > 2, "yes", "no"]

Everything in Wolfram Language is a Expression . That means, everything return a value, including the If function. There is no such thing as statements.

The If expression return the value of the part of expression it ran. e.g. If[3 > 2, 4, 5] returns 4.

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
]

Test Must Eval to Symbol True or Symbol False

Note: 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.

WolframLang Boolean

WolframLang in Depth

Basics

Comment, Print

String

Arithmetic

List

Expression, Atom, Head

Boolean

Conditional

Variable

Loop

Data Structure

Function

Pattern Matching

Advanced

Shell Tasks

Misc