Lesson 03 of 16

Operators & Strings

math, comparison, logic, f-strings

download this lesson (.md) ↓ all lessons

3. Operators & Strings

Arithmetic

print(10 + 3);   // 13
print(10 - 3);   // 7
print(10 * 3);   // 30
print(10 / 3);   // 3    (integer division when both are ints)
print(10 % 3);   // 1    (remainder)
print(2 * (3 + 4)); // 14 (parentheses group)

Comparison (give a bool)

print(5 == 5);   // true
print(5 != 3);   // true
print(3 < 5);    // true
print(5 <= 5);   // true
print(7 > 2);    // true
print(7 >= 9);   // false

Logic

&& (and), || (or), ! (not). The keywords and, or, not also work and read nicely:

print(true && false);    // false
print(true || false);    // true
print(!true);            // false
print(3 > 2 and 1 == 1); // true
print(not (5 > 10));     // true

&& and || short-circuit (the right side is only evaluated if needed).

Ternary

A compact if-expression: condition ? whenTrue : whenFalse.

let age = 20;
print(age >= 18 ? "adult" : "minor");   // adult

Membership: in

print(2 in [1, 2, 3]);     // true
print("ll" in "hello");    // true
print("k" in { "k": 1 });  // true (checks keys)

Strings

Concatenate with +. The other side is auto-converted:

let name = "Ada";
print("Hi " + name);        // Hi Ada
print("Age: " + 30);        // Age: 30

f-strings (string interpolation)

Put f before the quote; {expr} is evaluated and inserted:

let name = "Ada";
let age = 30;
print(f"{name} is {age} years old, next year {age + 1}.");
// Ada is 30 years old, next year 31.

String operations

let s = "Hello";
print(s.upper());      // HELLO
print(s.lower());      // hello
print(s.len());        // 5
print(s[0]);           // H   (indexing; negatives count from the end)
print(len(s));         // 5
print(upper("hi"), trim("  x  "), split("a,b,c", ","), join(["a","b"], "-"));

Next: Control Flow