Tern

2. Values and types

This chapter covers the building blocks every program uses: variables, the four basic types (int, float, bool, str), arithmetic, and conversions. The main thing to learn is that Tern infers types for you but never converts between them silently: when an int meets a float, you say which one you want.

Variables

A variable is created the first time you assign to it. There is no let, var, or const:

fn main():
    name = "Ada"
    age = 36
    height = 1.65
    likes_tea = true
    print(name, age, height, likes_tea)
    age = age + 1
    age += 1
    print(name, "is now", age)
Output
Ada 36 1.65 true
Ada is now 38

The compiler works out each variable's type from its first value: name is a str, age an int, height a float, and likes_tea a bool. That type is fixed from then on. Assigning a value of another type is an error, not a quiet change of meaning:

Does not compile
fn main():
    x = 1
    x = "one"
    y = 1 + 2.0
    print(x, y)
Compiler output
3: error: can't assign str to `x` of type int
4: error: `+` with mismatched types int and float (use float()/int() to convert)
4: hint: ints and floats never mix: `float(i) * x` or `i * int(x)`

You can write the type yourself with name: type = value. This is rarely needed for the basic types, but it documents intent, and it is how you create an empty collection (chapter 6):

fn main():
    ratio: float = 0.5
    count: int = 0
    tags: [str] = []
    print(ratio, count, tags)
Output
0.5 0 []

Every variable needs a value when it is created: x: int on its own is an error. Use a natural starting value such as 0, 0.0, false, or "".

There are no global variables. A value that never changes can be a constant, declared at the top level of the file with const; anything that changes is passed to the functions that use it:

const TAX_RATE = 0.2

fn main():
    price = 50.0
    print("tax:", price * TAX_RATE)
Output
tax: 10.0

Numbers

int is a 64-bit signed integer and float is a 64-bit floating-point number. A number with a dot is a float; without one it is an int. Floats need digits on both sides of the dot (1.0, 0.5), and underscores can group digits:

fn main():
    population = 8_100_000_000
    pi = 3.14159
    print(population, pi)
    print(7 + 2, 7 - 2, 7 * 2, 7 / 2, 7 % 2)
    print(7.0 / 2.0, -7 / 2, -7 % 3)
    print(0.1 + 0.2, 1.0 / 3.0)
Output
8100000000 3.14159
9 5 14 3 1
3.5 -3 -1
0.30000000000000004 0.3333333333333333

The rules worth remembering:

  • / on two ints is integer division. It truncates toward zero, so 7 / 2 is 3 and -7 / 2 is -3. There is no //.
  • % is the remainder, and its sign follows the left side.
  • There is no ** for powers; use math.pow (import math), or multiply.
  • Dividing an int by zero is a runtime error. int arithmetic wraps around on overflow rather than stopping the program.
  • Floats print with at least one decimal (10.0), using the shortest form that reads back exactly. That is why 0.1 + 0.2 shows its rounding error, just as in Python or JavaScript.

No implicit conversions

In most languages 1 + 2.5 quietly turns the 1 into a float. Tern refuses, because this kind of silent conversion hides bugs (integer division where you wanted a fraction, or a fraction truncated where you wanted a whole number). You convert explicitly:

fn main():
    total = 7
    count = 2
    avg = float(total) / float(count)
    print(avg)
    print(int(avg), int(-2.7))
    print(float(total) * 1.5)
Output
3.5
3 -2
10.5

float(i) turns an int into a float. int(f) turns a float into an int by dropping the fraction (toward zero). For rounding, use math.round, math.floor, or math.ceil.

Booleans

bool has two values, written true and false in lowercase. Combine them with the words and, or, and not (there is no &&, ||, or !):

fn main():
    temp = 22
    sunny = true
    good_day = sunny and temp > 18 and temp < 30
    print(good_day, not good_day, temp == 22, temp != 22)
    print(temp >= 30 or sunny)
Output
true false true false
true

and and or short-circuit: the right side runs only if it is needed. Comparisons (==, !=, <, <=, >, >=) work on numbers and on strings. There is no "truthiness": an if needs a real bool, so write if len(xs) > 0: rather than if xs:.

Strings

A str is text in double quotes. + joins two strings; * repeats one. To put another kind of value into a string, use str(x) or an f-string, which evaluates each {...}:

fn main():
    first = "Grace"
    last = "Hopper"
    full = first + " " + last
    born = 1906
    print(full)
    print(full + " was born in " + str(born))
    print(f"{full} was born in {born}, {2024 - born} years ago")
    print("-" * 20)
    print("tab:\tquote:\" backslash:\\")
Output
Grace Hopper
Grace Hopper was born in 1906
Grace Hopper was born in 1906, 118 years ago
--------------------
tab:	quote:" backslash:\

Strings use double quotes only, and a string must fit on one line (use \n for a line break). The usual escapes work: \n, \t, \", \\, and \u00e9 or \u{1F600} for any Unicode character. Chapter 7 covers strings in depth: slicing, searching, splitting, and formatting numbers.

Comments

A comment starts with # and runs to the end of the line. There are no block comments or docstrings; write several # lines.

Mistakes from other languages

Because Tern looks like Python, Python habits are the most common source of errors. The compiler recognizes many of them and says what to write instead:

Does not compile
fn main():
    ok = True
    print(ok)
Compiler output
2: error: unknown variable `True`
2: hint: booleans are lowercase: `true`

Only the first error is shown here because the program could not be parsed past line 3. After fixing it, check reports the next one: unknown variable True, with the hint "booleans are lowercase: true".

Try it

A recipe needs 250 grams of flour for 4 people. Write a program that takes a number of people in a variable guests (an int) and prints how much flour to use, as a float. Then print it again rounded down to whole grams, as an int. For 6 guests the answer is 375.0 grams. Make sure the computation does not lose the fraction for, say, 3 guests.

Solution

fn main():
    grams_for_4 = 250
    for guests in [3, 6]:
        flour = float(grams_for_4) * float(guests) / 4.0
        print(f"{guests} guests: {flour} g (about {int(flour)} g)")
Output
3 guests: 187.5 g (about 187 g)
6 guests: 375.0 g (about 375 g)

Writing grams_for_4 * guests / 4 would compute with ints and give 187 for 3 guests.

Next: 3. Control flow. Reference: §2 Lexical rules, §3 Variables and types, §4 Operators.

Source: docs/tour/02-values-and-types.md. Every example on this page is compiled and run by tern x test docs.