If Else in Wolfram Language

(* Branching with If and Else in Wolfram Language is straightforward. *)

(* Here's a basic example. *)
If[Mod[7, 2] == 0,
  Print["7 is even"],
  Print["7 is odd"]
]

(* You can have an If statement without an Else. *)
If[Mod[8, 4] == 0,
  Print["8 is divisible by 4"]
]

(* Logical operators like && and || are often useful in conditions. *)
If[Mod[8, 2] == 0 || Mod[7, 2] == 0,
  Print["either 8 or 7 are even"]
]

(* In Wolfram Language, you can use Block to create a local variable
   that's available in the current and subsequent branches. *)
Block[{num = 9},
  If[num < 0,
    Print[num, " is negative"],
    If[num < 10,
      Print[num, " has 1 digit"],
      Print[num, " has multiple digits"]
    ]
  ]
]

When you run this code in a Wolfram Language environment, you’ll see the following output:

7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

In Wolfram Language, the If function is used for conditional branching. It takes the form If[condition, then-expression, else-expression]. The else-expression is optional.

Unlike some other languages, Wolfram Language doesn’t use curly braces {} to denote blocks of code. Instead, expressions are typically grouped using square brackets [].

Wolfram Language doesn’t have a direct equivalent to Go’s ability to declare a variable in an if statement. However, you can use Block to create a local variable scope, as demonstrated in the last example.

Note that Wolfram Language is a functional programming language, so these examples use Print to show output. In practice, you might often use these conditional expressions to compute and return values rather than for side effects like printing.

Wolfram Language also supports more advanced pattern-based conditional constructs like Switch and Which, which can be very powerful for complex conditional logic.