Skip to content
AgileLogics
6 min read

Logic and Conditionals

Prerequisites: Variables and assignment

Comparisons

3 == 3
3 != 4
2 < 3 < 4
True && False
True || False
!True
True
True
True
False
True
False
  • == tests equality (a single = assigns).
  • && is and, || is or, ! is not.
  • Comparisons can be chained: 2 < 3 < 4.

Symbolic equations stay unevaluated

If the answer isn't known, == stays as an equation — that's how you write equations for Solve:

Clear[x]
x == 5
x === 5
x == 5
False

=== (SameQ) asks "are these literally the same expression?" and always returns True or False. Use it in program logic when a value might be symbolic.

If

If[condition, then, else] is a function that returns a value:

n = 7;
If[EvenQ[n], "even", "odd"]
parity = If[n > 5, "big", "small"];
parity
odd
big

If the condition is neither True nor False, If stays unevaluated: If[y > 0, 1, -1] with no value for y returns itself. A fourth argument handles that case: If[cond, a, b, other].

Which and Switch

sign[v_] := Which[v < 0, "negative", v == 0, "zero", True, "positive"]
{sign[-3], sign[0], sign[8]}

size[k_] := Switch[k, 1, "one", 2, "two", _, "many"]
{size[1], size[2], size[9]}
{negative, zero, positive}
{one, two, many}
  • Which[test1, value1, test2, value2, ...] returns the value for the first true test; True at the end acts as "otherwise".
  • Switch[expr, form1, value1, ...] compares expr against patterns; _ matches anything.
  • sign[v_] := ... defines a function — the next lessons explain it fully.

Practice

Write an expression that gives "fizz" for multiples of 3, "buzz" for multiples of 5, "fizzbuzz" for both, and the number otherwise, and try it on 9, 10, 15, and 7.

Show solution
fb[n_] := Which[
  Mod[n, 15] == 0, "fizzbuzz",
  Mod[n, 3] == 0, "fizz",
  Mod[n, 5] == 0, "buzz",
  True, n]
{fb[9], fb[10], fb[15], fb[7]}
{fizz, buzz, fizzbuzz, 7}