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
parityreturns the whole branch as a single expression.- The same form works inline when assigning
size. - Both arms have to produce the same type.
Keywords and builtins used here
IntStringdefelseforifmainparityprintrangereturnvar
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.
Step 5 of 5 in Flow control, step 11 of 26 in Language basics.