Learn/Nim/1. Hello, output
Lesson 1 of 8
Sign in

Nim, lesson 1

Hello, output

The quickest way to see a Nim program do something is echo. It writes its arguments to the screen and finishes with a line break.

echo is a procedure (Nim's word for a function) that is always available, so you don't need to import anything. You can call it with or without parentheses: echo("hi") and echo "hi" are the same. Text in double quotes is a string.

Several things at once

echo accepts several arguments separated by commas. It converts each one to text and writes them one after another, without adding spaces between them:

If you want spaces, put them inside the strings yourself, as above.

Staying on the same line

echo always ends the line. To keep writing on the same line, use stdout.write, which prints exactly what you give it:

2 exercises to try what you just read.

Exercise 1

Your first program

Press Ctrl Enter or Check to test your code.

Exercise 2

Countdown on one line

Press Ctrl Enter or Check to test your code.

stdout is the program's standard output, the same place echo writes to. You can also put a line break inside a string with \n.

Comments

A # starts a comment that runs to the end of the line. For longer notes, wrap text in #[ and ]#. Nim ignores both.

A ## comment is a documentation comment; tools use it to build docs for your code.

How a Nim program runs

Nim is a compiled language. Your file, main.nim, is first translated into C and then into a native program, which then runs. That is why the first run takes a moment, and why the result is fast. The compiler also catches many mistakes, such as misspelled names or mixing up text and numbers, before your program ever starts.

The program itself runs the top-level statements of the file in order, from the first line to the last. Indentation matters in Nim: blocks of code are marked by indenting them, like in Python, so keep your spacing consistent (two spaces is the usual style).

Further reading

  • Nim Tutorial (Part I): the first program and comments
  • The system module (home of echo and stdout)

Write a program that prints exactly these two lines:

The program reads no input.

A rocket launch counts down on a single line. Print this, followed by one line break:

Use stdout.write for each number (each one ends with ... , three dots and a space) and a single echo for Liftoff!. The starter uses echo everywhere, so every piece lands on its own line. Fix it.

echo "Hello, World!"
echo "Nim runs this line second."
echo "Score: ", 42          # Score: 42
echo 3, " apples and ", 5, " pears"
stdout.write "Loading"
stdout.write "..."
echo "done"            # Loading...done
# Greet the user first.
echo "Welcome!"   # a comment can follow code

#[
  A comment that spans
  several lines.
]#
Hello, World!
I am learning Nim.
3... 2... 1... Liftoff!