3. Control flow
This chapter shows how a Tern program makes decisions and repeats work: if/elif/else, for loops over ranges and collections, while loops, and break, continue, and pass. It also explains one rule that surprises Python programmers: a variable created inside a block ends with that block.
if, elif, else
Conditions don't need parentheses. Each branch ends with : and an indented block:
fn main():
temp = 31
if temp > 30:
print("hot")
elif temp > 15:
print("mild")
else:
print("cold")
if temp % 2 == 1: print("odd degrees")hot
odd degreesA block with a single statement may go on the same line as its :, as in the last line. Use this sparingly; most code reads better with the block on its own line.
It is elif, never else if. The condition must be a bool: if count: is an error; write if count > 0:.
To choose between two values, use a conditional expression, as in Python: label = "big" if x > 2 else "small". Only the chosen side is evaluated. (There is no c ? a : b.) An if statement that assigns a variable does the same job for longer code, which brings us to scope.
Where variables live
A variable lives from its first assignment to the end of the block it was created in. So this does not compile:
fn main():
score = 72
if score >= 50:
result = "pass"
else:
result = "fail"
print(result)7: error: unknown variable `result`Each result exists only inside its own branch. The fix is to create the variable before the if, with a starting value, and then assign to it:
fn main():
score = 72
result = "fail"
if score >= 50:
result = "pass"
print(result)passThis rule makes it impossible to read a variable that was only set on some paths, which is a common bug in languages where it is allowed.
for loops over ranges
for i in a..b: counts from a up to, but not including, b. There is no range():
fn main():
for i in 0..3:
print("round", i)
total = 0
for n in 1..101:
total += n
print("1 + 2 + ... + 100 =", total)
for i in 5..5:
print("never printed")round 0
round 1
round 2
1 + 2 + ... + 100 = 5050A range whose start is not below its end runs zero times. There is no step value; to count down or skip numbers, use a while loop (below).
Inside the loop, the loop variable is read-only: assigning i = 5 is an error, because it would not do what it looks like (the next round would not continue from 5).
for loops over collections
for x in xs: visits each element of an array, and for i, x in xs: also gives the index. Arrays get their own chapter (chapter 6), but loops over them are too useful to wait for:
fn main():
planets = ["Mercury", "Venus", "Earth"]
for p in planets:
print(p)
for i, p in planets:
print(i + 1, p)
letters = 0
for ch in "Earth":
letters += 1
print(letters, "letters")Mercury
Venus
Earth
1 Mercury
2 Venus
3 Earth
5 lettersA for over a string visits it one byte at a time, as a one-byte str. Loops over maps (for key, value in m:) are covered with maps.
while loops
while repeats as long as its condition is true. Use it when you don't know the number of rounds in advance, or when a range doesn't fit, such as counting down:
fn main():
n = 27
steps = 0
while n != 1:
if n % 2 == 0:
n = n / 2
else:
n = 3 * n + 1
steps += 1
print("27 reaches 1 after", steps, "steps")
i = 3
while i > 0:
print(i)
i -= 1
print("liftoff")27 reaches 1 after 111 steps
3
2
1
liftoffThere is no do ... while or loop. Write while true: and leave with break.
break, continue, and pass
break leaves the innermost loop. continue skips to its next round. pass does nothing; it fills a block that must exist but has nothing to do:
fn main():
readings = [12, -1, 15, 99, 14, 13]
total = 0
for r in readings:
if r < 0:
continue # a bad reading: skip it
if r == 99:
break # 99 marks the end of the data
total += r
print("total", total)
while true:
total -= 10
if total < 0:
break
print("after", total)
if total > 100:
pass # nothing to do yettotal 27
after -3Mistakes from other languages
The compiler knows the usual alternatives and points you to the Tern way:
fn main():
for i in range(3):
print(i)2: error: unknown function `range`
2: hint: there is no range(): write `for i in 0..n:` (or `for i in a..b:`; the end is exclusive)fn main():
x = 3
label = x > 2 ? "big" : "small"
print(label)3: error: expected end of line, found 'big'
3: hint: there is no `c ? a : b`; write `a if c else b`Try it
Write FizzBuzz for 1 to 15: print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, and the number otherwise. Then change the program to stop at the first number above 10 that is a multiple of 3, using break.
Solution
fn main():
for i in 1..16:
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzzFor the second part, add if i > 10 and i % 3 == 0: break at the top of the loop body.
Next: 4. Functions. Reference: §5 Control flow.