typestar

Conditional expressions in Mojo

a if cond else b picks a value without opening a block.

def parity(n: Int) -> String:
    return "even" if n % 2 == 0 else "odd"

def main():
    for n in range(1, 6):
        var size = "big" if n > 3 else "small"
        print(n, parity(n), size)

How it works

  1. parity returns the whole branch as a single expression.
  2. The same form works inline when assigning size.
  3. Both arms have to produce the same type.

Keywords and builtins used here

The run, in numbers

Lines
7
Characters to type
168
Tokens
61
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 41 seconds.

Type this snippet

Step 5 of 5 in Flow control, step 11 of 26 in Language basics.

← Previous Next →

Conditional expressions in other languages