Learn/Nim/4. Making decisions
Lesson 4 of 8
Sign in

Nim, lesson 4

Making decisions

Programs constantly make choices: is the password long enough, did the player win, is the shop open? Nim gives you if and case for this.

Comparisons and booleans

OperatorMeaning
== / !=equal / not equal
<, <=, >, >=ordering
and, or,

2 exercises to try what you just read.

Exercise 1

Letter grade

Press Ctrl Enter or Check to test your code.

Exercise 2

Leap year

Press Ctrl Enter or Check to test your code.

not
combine or flip booleans

Each comparison produces a bool. and and or short-circuit: in a and b, Nim does not even look at b when a is already false. Unlike some languages, Nim does not treat 0 or "" as false; a condition must be a real bool.

if, elif, else

Each branch ends with a colon, and its body is indented. Nim checks the conditions from top to bottom and runs the first one that is true:

if can also be used as an expression that produces a value. Then every path needs an else:

case: pick a branch by value

When one value decides between many branches, case is cleaner than a chain of elifs. Each of lists one or more values, or a range like 1..5:

The compiler insists that a case covers every possible value. An int has billions of values, so you almost always need an else. That rule is a safety net: you can't forget a case by accident.

Like if, case can be an expression: write let label = followed by the case on the next lines, and let each branch end with the value it produces instead of an echo.

Further reading

  • Nim Tutorial (Part I): control flow statements
  • Nim Manual: case statement

Read a test score and print its letter grade:

  • 90 to 100: A
  • 80 to 89: B
  • 70 to 79: C
  • 60 to 69: D
  • 0 to 59: F
  • below 0 or above 100: Invalid

Input: one line with a whole number. Output: the grade on one line. For 85, print B. A case with ranges fits this perfectly.

A year is a leap year if it is divisible by 4, except years divisible by 100, which are not, unless they are also divisible by 400. So 2024 and 2000 are leap years, but 1900 is not.

Input: one line with a year. Output: leap or common.

let age = 20
let member = true
echo age >= 18 and member   # true
echo not member             # false
let temp = 31
if temp > 25:
  echo "It's hot!"
elif temp > 15:
  echo "It's mild."
else:
  echo "Bring a jacket."
let advice = if temp > 25: "Wear a hat" else: "Bring a jacket"
let dice = 4
case dice
of 1: echo "Ouch"
of 2, 3: echo "Meh"
of 4..6: echo "Nice roll"
else: echo "That's not a die"