3. Control flow and functions
Making decisions
fn sign(n):
if n > 0:
return "positive"
elif n < 0:
return "negative"
else:
return "zero"
print(sign(3))
print(sign(-8))
print(sign(0))
# => positive
# => negative
# => zero
The body of an if is not a separate scope — a variable you assign there is
still around afterwards:
if true:
message = "set inside the if"
print(message)
# => set inside the if
Repeating work
while repeats while a condition holds; for walks a list, string, map, or
range:
n = 5
factorial = 1
while n > 1:
factorial = factorial * n
n = n - 1
print(factorial)
# => 120
for word in ["one", "two", "three"]:
print(word)
# => one
# => two
# => three
range(n) gives [0, 1, ..., n-1]; range(a, b) and range(a, b, step) give
the rest of what you would expect:
total = 0
for i in range(1, 101):
total = total + i
print(total)
# => 5050
break leaves a loop; continue skips to its next turn.
Functions
fn defines one. Parameters are positional, and a call must pass exactly the
right number:
fn greet(greeting, who):
return greeting + ", " + who + "!"
print(greet("Hello", "world"))
# => Hello, world!
A function with no return (or a bare return) gives back nil.
Functions are values
You can pass a function to another function, return one, or store one in a list:
fn twice(f, x):
return f(f(x))
fn inc(n):
return n + 1
print(twice(inc, 10))
# => 12
Closures
A function defined inside another one remembers the variables around it — and can change them:
fn make_counter():
count = 0
fn next():
count = count + 1
return count
return next
tick = make_counter()
print(tick())
print(tick())
print(tick())
# => 1
# => 2
# => 3