Lesson 04 of 16

Control Flow

if/elif/else, while, for, foreach, loop, ternary

download this lesson (.md) ↓ all lessons

4. Control Flow

if / elif / else

let n = 7;
if (n > 10) {
    print("big");
} elif (n > 5) {
    print("medium");
} else {
    print("small");
}

Parentheses around the condition are optional:

if n > 5 {
    print("more than five");
}

while

let i = 0;
while (i < 3) {
    print("i =", i);
    i = i + 1;
}

for — C-style

for (let i = 0; i < 5; i = i + 1) {
    print(i);   // 0 1 2 3 4
}

for — ranges

for also accepts a range directly, not just a list:

for i in 0..10 {
    if (i == 5) { break; }
    if (i % 2 == 0) { continue; }
    print(i);   // 1 3
}

for ... in — foreach

Iterate a list, a string (its characters), or a dict (its keys):

for x in [10, 20, 30] {
    print(x);
}
for ch in "abc" {
    print(ch);
}
for key in { "a": 1, "b": 2 } {
    print(key);
}

loop ... in — ranges

a..b goes from a up to (but not including) b:

loop i in 0..5 {
    print(i);   // 0 1 2 3 4
}

loop { ... } with no range is an infinite loop.

Ternary expression

let x = 8;
let label = x % 2 == 0 ? "even" : "odd";
print(label);   // even

break and continue

break exits the loop early; continue skips to the next iteration. Both work in while, the C-style for, for ... in (lists, ranges, strings, dicts), and loop:

for i in 0..10 {
    if (i == 5) { break; }        // stop the loop entirely
    if (i % 2 == 0) { continue; } // skip the rest of this iteration
    print(i);   // 1 3
}
func firstEven(list) {
    let found = null;
    for x in list {
        if (x % 2 == 0) { found = x; break; }
    }
    return found;
}
print(firstEven([1, 3, 6, 9]));   // 6

Next: Functions