The Zeno Book Zeno 0.1 zeno-lang.org

7 Deciding and Repeating

A program that only goes from the top to the bottom can only do one thing. This chapter is about the two things that change that: doing a block only when something is true, and doing a block again and again.

7.1 if

let temperature = 31
if temperature > 30 {
    print("hot")
}
hot

The block runs only when the condition is true. There is no : after the condition and no need for brackets around it: the { already says where the condition ends.

else gives a block for when it is false, and else if asks again:

function describe(t: int) -> str {
    if t < 0 {
        return "freezing"
    } else if t < 18 {
        return "cold"
    } else if t < 25 {
        return "comfortable"
    } else {
        return "hot"
    }
}

for t in [-5, 10, 21, 31] {
    print(t, describe(t))
}
-5 freezing
10 cold
21 comfortable
31 hot

There is one way to write it, so elif gets a message:

let x = 2
if x == 1 {
    print("one")
} elif x == 2 {
    print("two")
}
error: Zeno spells `elif` as `else if`
 --> main.zeno:4:3
  |
4 | } elif x == 2 {
  |   ^

With braces, } else if x { reads as plain words and needs no keyword of its own. (Decision 1.8.) The braces themselves are there because where a block ends should be written down, not implied by spaces that can be lost when code is pasted into an e-mail. (Decision 1.1.)

The condition must be a bool. if count for a number, or if items for a list, is refused; write what you mean, count != 0 or len(items) > 0 (Numbers and Operators).

7.2 while

while runs its block again and again for as long as its condition is true. The condition is asked before each turn:

var n = 1
while n < 100 {
    n *= 3
}
print(n)
243

A loop that should run until something inside it says stop is written while true, with a break:

var tries = 0
while true {
    tries += 1
    if tries * tries > 50 {
        break
    }
}
print(tries)
8

7.3 for

for goes through the items of something, one at a time:

for name in ["Ada", "Grace", "Alan"] {
    print("hello,", name)
}
hello, Ada
hello, Grace
hello, Alan

The name after for is new for each turn, belongs to the loop, and is gone after it. It cannot be given another value inside the loop.

A for loop can go through a list, the characters of a text, the keys of a dict, or a range of numbers.

range

range gives a list of whole numbers. With one number it counts from 0 up to, not including, that number. With two it counts from the first up to the second. A third number is the step, which may be negative:

print(range(5), range(2, 5), range(10, 0, -3), range(0))
for i in range(3) {
    print("turn", i)
}
[0, 1, 2, 3, 4] [2, 3, 4] [10, 7, 4, 1] []
turn 0
turn 1
turn 2

The position and the item

With two names, a for loop is given the position of each item and the item itself. The rule is the same for everything a loop can go through: the second name is what is at the first.

for at, word in ["zero", "one", "two"] {
    print(at, word)
}
for trip, n in range(10, 0, -4) {
    print(trip, n)
}
0 zero
1 one
2 two
0 10
1 6
2 2

Over a dict, the first name is the key and the second the value under it (Dicts).

Without this, the position is a var counted by hand beside the loop, or for i in range(len(words)) and words[i] on the next line: two ways, both longer than what they mean. Python’s enumerate and items are two more names to learn, and each builds pairs that Zeno has no type for. (Decision 10.12.)

The loop sees the list as it was

A for loop goes through the list as it was when the loop began. Adding to the list, or taking from it, inside the loop does not change which items the loop visits:

var xs = [1, 2, 3]
for x in xs {
    xs.append(x * 10)
}
print(xs)
[1, 2, 3, 10, 20, 30]

The other choice, looping over the list as it changes, is the source of two classic mistakes: a loop that never ends because its body keeps appending, and a loop that skips an item because its body removed one. (Decision 3.10a.)

7.4 break and continue

break leaves the loop at once. continue skips the rest of this turn and goes on with the next. Both work in while and for, and both act on the innermost loop they are in:

for n in range(1, 20) {
    if n % 2 == 0 {
        continue        # skip the even ones
    }
    if n > 9 {
        break           # and stop after 9
    }
    print(n)
}
1
3
5
7
9

A break outside a loop is a mistake:

break
error: `break` outside a loop
 --> main.zeno:1:1
  |
1 | break
  | ^

1 error found. Nothing was run.

7.5 Loops inside loops

for row in range(1, 4) {
    var line = ""
    for column in range(1, 4) {
        line = line + f"{row * column:4}"
    }
    print(line)
}
1   2   3
   2   4   6
   3   6   9

7.6 A worked example: primes

Putting the pieces together, this program finds the prime numbers below 50. A number is prime when nothing from 2 up to its square root divides it:

primes.zeno

function is_prime(n: int) -> bool {
    if n < 2 {
        return false
    }
    var d = 2
    while d * d <= n {
        if n % d == 0 {
            return false
        }
        d += 1
    }
    return true
}

var found: list[int] = []
for n in range(50) {
    if is_prime(n) {
        found.append(n)
    }
}
print(found)
print(len(found), "primes below 50")
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
15 primes below 50

if, else if and else choose a block. while repeats a block while a condition holds, and for goes through the items of a list, a text, a dict or a range, with an optional second name for the position or the key. A for loop sees its list as it was when it began. break leaves a loop and continue starts its next turn.

  1. Print the numbers from 1 to 30, with fizz for those that 3 divides, buzz for those that 5 divides, and fizzbuzz for those both divide.

  2. Change the primes program to stop as soon as it has found ten primes, using break.

  3. Write a loop that appends to the list it walks through, and check that it ends. Then write the same with while and an index, and see that it does not.

  4. Print a triangle of * five lines high, with a loop inside a loop.