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

Elixir, lesson 1

Hello, output

Your first job in any language is to make the program say something. In Elixir you do that with IO.puts. IO is a module (a named group of functions) that ships with Elixir, and puts is one of its functions. It writes a value to the screen and then moves to a new line.

Text inside double quotes is a string. Elixir strings always use double quotes. Single quotes mean something else (an old-style character list), so stay away from them for now.

Parentheses are optional

In Elixir you may leave out the parentheses around a function's arguments. These two lines do the same thing:

Most Elixir code keeps the parentheses, and so will this course. They make it obvious where a call starts and ends.

Staying on the same line

IO.puts always adds a line break at the end. When you want to keep writing on the same line, use IO.write. It prints exactly what you give it and nothing more:

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.

You can also put the line break into the string yourself with \n. The string "one\ntwo" prints on two lines.

Comments

A # starts a comment. Elixir ignores everything from the # to the end of the line. Use comments to explain why your code does something.

How a script runs

Your code lives in a file called main.exs. The .exs ending marks an Elixir script: a file that Elixir reads and runs straight away, from the first line to the last, without a separate build step. Every expression in Elixir returns a value; IO.puts returns the atom :ok once it has printed, but you can ignore that for now.

If something is wrong, Elixir stops and prints an error that names the problem and the line where it happened. Read the message slowly: it usually tells you exactly what to fix.

Further reading

  • Getting started: Introduction
  • The IO module

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 IO.write for each number (each one ends with ... , three dots and a space) and a single IO.puts for Liftoff!. The starter uses IO.puts everywhere, so every piece lands on its own line. Fix it.

IO.puts("Hello, World!")
IO.puts("Elixir runs this line second.")
IO.puts("with parentheses")
IO.puts "without parentheses"
IO.write("Loading")
IO.write("...")
IO.puts("done")
# Loading...done
# Greet the user before anything else happens.
IO.puts("Welcome!")  # comments can follow code too
Hello, World!
I am learning Elixir.
3... 2... 1... Liftoff!