If Else in Nim

Branching with if and else in Nim is straightforward.

import std/strformat

proc main() =
  # Here's a basic example.
  if 7 mod 2 == 0:
    echo "7 is even"
  else:
    echo "7 is odd"

  # You can have an `if` statement without an else.
  if 8 mod 4 == 0:
    echo "8 is divisible by 4"

  # Logical operators like `and` and `or` are often
  # useful in conditions.
  if 8 mod 2 == 0 or 7 mod 2 == 0:
    echo "either 8 or 7 are even"

  # A variable declaration can precede conditionals;
  # any variables declared here are available in the current
  # and all subsequent branches.
  let num = 9
  if num < 0:
    echo fmt"{num} is negative"
  elif num < 10:
    echo fmt"{num} has 1 digit"
  else:
    echo fmt"{num} has multiple digits"

main()

To run the program, save it as if_else.nim and use the Nim compiler:

$ nim c -r if_else.nim
7 is odd
8 is divisible by 4
either 8 or 7 are even
9 has 1 digit

Note that in Nim, you don’t need parentheses around conditions, but indentation is used to define blocks instead of braces. Also, Nim uses and and or instead of && and || for logical operations.

Nim does have a ternary operator-like construct called the “if expression”:

let result = if condition: trueValue else: falseValue

This can be used for simple conditional assignments, similar to the ternary operator in other languages.

In Nim, the mod operator is used for modulus operations instead of the % symbol used in many other languages.