if, elif, else
The conditional statement looks like Python. An if line, a condition, a colon, and an indented body.
if score >= 90:
print("great")
elif score >= 50:
print("ok")
else:
print("try again")
Three rules:
- The condition must be a
Bool. A number likeif score:won't compile. Useif score != 0:orif Bool(score):instead. - There can be any number of
elifbranches, including none.elseis optional. elifandelsemust be indented at the same column as theirif. The compiler checks this.
A complete example:
def grade(score: Int32) -> NoneType
if score >= 90:
print("great")
elif score >= 50:
print("ok")
else:
print("try again")
return
def main() -> Int32
grade(95)
grade(60)
grade(20)
return 0
Variables and branches
If a variable is declared inside a branch and you want to use it afterwards, declare it in every branch. The compiler merges the values. This rule is explained with a working example on the Variables page.
Division by zero at compile time
When the compiler can see that you're dividing by the constant zero, it rejects the code before running it:
x: Int32 = 1 / 0 # compile error
This applies to /, //, and %. If the divisor comes from somewhere the compiler can't check, like user input, the check happens at runtime instead, and only in debug mode. Without debug mode it's undefined behavior.
Recursion
A recursion example:
def fact(n: Int32) -> Int32
if n <= 1:
return 1
return n * fact(n - 1)
def main() -> Int32
print(fact(5))
return 0
Deep recursion can hit stack limits, so keep the depth sane. Loops are a planned feature, listed in the Limits page.