Skip to content

Mojo If...Else

Most programs need to make choices: show a warning if the battery is low, give a discount if the customer is a student, stop if the file is missing. In Mojo you make those choices with if, elif and else. If you know Python, this will look almost exactly the same, with one difference about variables that we’ll get to near the end.

An if checks a condition. When the condition is True, the indented block under it runs. When it’s False, the block is skipped:

def main():
var battery = 15
if battery < 20:
print("Battery is low.")
print("Plug in your charger.")
print("Battery:", battery)

Output:

Battery is low.
Plug in your charger.
Battery: 15

The condition is battery < 20. It’s True here, so both indented lines run. The last print isn’t indented under the if, so it always runs. Change battery to 80 and only Battery: 80 is printed.

The condition can be anything that gives a Bool (True or False), like a comparison with <, >, <=, >=, == or !=.

else gives you a block that runs when the condition is False. Exactly one of the two blocks runs, never both:

def main():
var age = 15
if age >= 18:
print("You can vote.")
else:
print("You can vote in", 18 - age, "years.")

Output:

You can vote in 3 years.

else has no condition of its own. It catches every case the if didn’t.

When there are more than two options, add elif (short for “else if”) branches. Mojo checks them from top to bottom and runs the first one that’s True. The rest are skipped:

def main():
var score = 84
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")

Output:

Grade: B

84 >= 90 is False, so Mojo moves on. 84 >= 80 is True, so it prints Grade: B and jumps past the whole chain. It never even looks at score >= 70, although that would also be True.

You can have as many elif branches as you like, and the else at the end is optional.

Use and, or and not to build bigger conditions, just like in Python:

def main():
var age = 20
var has_ticket = True
if age >= 18 and has_ticket:
print("Come in.")
if age < 13 or age >= 65:
print("You get a discount.")
else:
print("Full price.")
if not has_ticket:
print("Please buy a ticket first.")

Output:

Come in.
Full price.
  • and is True only when both sides are True.
  • or is True when at least one side is True.
  • not flips True to False and back.

For a range check, you can chain comparisons the way you would in math. 0 < temp < 30 means “temp is above 0 and below 30”:

def main():
var temp = 18
if 0 < temp < 30:
print("Nice weather.")

Output:

Nice weather.

If the left side of and is False, the whole thing is False, so Mojo doesn’t run the right side at all. The same goes for or when the left side is True. This is called short-circuit evaluation:

def is_admin(name: String) -> Bool:
print("Checking", name)
return name == "admin"
def main():
var logged_in = False
if logged_in and is_admin("ana"):
print("Welcome, admin.")
else:
print("Please log in.")

Output:

Please log in.

Checking ana never appears, because logged_in is already False. This is handy: put the cheap or safe check on the left, and the slow or risky one on the right. The official control flow page in the Mojo manual has more examples of this.

You don’t always have to write a comparison. Numbers, strings and lists can go straight into an if. A zero, an empty string or an empty list counts as False, and everything else counts as True, the same rule Python uses:

def main():
var name = ""
var items: List[Int] = [4, 7]
var errors = 0
if name:
print("Hello,", name)
else:
print("No name given.")
if items:
print("You have", len(items), "items.")
if not errors:
print("No errors.")

Output:

No name given.
You have 2 items.
No errors.

if items: reads as “if there are any items”. It’s shorter than if len(items) > 0:, and it’s what most Python and Mojo code does.

Picking a value: the conditional expression

Section titled “Picking a value: the conditional expression”

Often you only want to choose between two values. Instead of a four-line if/else, you can write it on one line, in this order: value_if_true if condition else value_if_false.

def main():
var n = 7
var kind = "even" if n % 2 == 0 else "odd"
print(n, "is", kind)

Output:

7 is odd

People coming from C or JavaScript know this as the “ternary operator” (cond ? a : b). Mojo uses Python’s word order instead.

Both sides have to be the same kind of value. A string on one side and a number on the other doesn’t work:

def main():
var stock = 5
var label = "in stock" if stock > 0 else 0
print(label)
hello.mojo:3:28: error: value of type 'StringLiteral["in stock"]' is not compatible with value of type 'IntLiteral[0]'
var label = "in stock" if stock > 0 else 0
~~~~~~~~~~ ^ ~
mojo: error: failed to parse the provided Mojo source module

Python would let this through and hand you a value that’s sometimes a string and sometimes a number. Mojo checks types before the program runs, so it stops you here. Use "sold out" instead of 0 and it works.

Here’s the one real difference from Python. In Python, a variable you create inside an if block is still there after the block. In Mojo, a variable declared with var inside a block only lives inside that block:

def main():
var temp = 31
if temp > 25:
var advice = "Stay in the shade."
print(advice)
hello.mojo:5:11: error: use of unknown declaration 'advice'
print(advice)
^~~~~~
mojo: error: failed to parse the provided Mojo source module

The fix is to declare the variable before the if, and give it a value in every branch:

def main():
var temp = 31
var advice: String
if temp > 25:
advice = "Stay in the shade."
else:
advice = "Enjoy the sun."
print(advice)

Output:

Stay in the shade.

var advice: String creates the variable without a value yet. Each branch then fills it in. If you forget the else, Mojo notices that advice might still be empty when you print it:

def main():
var temp = 31
var advice: String
if temp > 25:
advice = "Stay in the shade."
print(advice)
hello.mojo:6:10: error: use of uninitialized value 'advice'
print(advice)
^
hello.mojo:3:9: note: 'advice' declared here
var advice: String
^
mojo: error: failed to run the pass manager

That’s a bug Python would only show you at run time, and only on a cold day. Mojo finds it before the program even starts. (For a simple choice like this one, the conditional expression from the last section is even shorter.)

Two habits from other languages give quick errors in Mojo.

Using = instead of ==. A single = assigns a value; it can’t be a condition:

def main():
var x = 5
if x = 5:
print("five")
hello.mojo:3:10: error: expected ':' after 'if' condition
if x = 5:
^
mojo: error: failed to parse the provided Mojo source module

Writing else if instead of elif:

def main():
var x = 5
if x > 10:
print("big")
else if x > 3:
print("medium")
hello.mojo:5:10: error: expected ':' after else
else if x > 3:
^
mojo: error: failed to parse the provided Mojo source module

In both cases, the error points right at the problem. Write == to compare, and elif for “else if”. A missing : at the end of the if line gives the same “expected ‘:’” error.

The compound statements reference has the exact rules for if, including the one-line form if x > 0: print("positive").

Write a program with var n = 12 that prints 12 is even. Use a conditional expression, not an if statement. Then try it with n = 7.

Hint: a number is even when n % 2 == 0.

Show solution
def main():
var n = 12
var kind = "even" if n % 2 == 0 else "odd"
print(n, "is", kind)

Output:

12 is even

The conditional expression picks "even" or "odd" in one line, and print puts spaces between its values.

A cinema charges 5 for children under 12, 6 for people 65 and over, and 10 for everyone else. On Tuesdays, everyone pays 5. Write a program with var age = 30 and var is_tuesday = False that prints Price: 10.

Hint: check the Tuesday rule first, and combine the two cheap cases with or.

Show solution
def main():
var age = 30
var is_tuesday = False
var price: Int
if is_tuesday or age < 12:
price = 5
elif age >= 65:
price = 6
else:
price = 10
print("Price:", price)

Output:

Price: 10

price is declared before the if so it still exists after it, and every branch gives it a value. Try age = 70, and then is_tuesday = True.

This program should print Too cold, but it doesn’t compile. Fix it.

def main():
var temp = 4
if temp < 10:
var message = "Too cold"
else if temp > 30:
var message = "Too hot"
print(message)

Hint: there are two problems: one with else if, and one with where message lives.

Show solution
def main():
var temp = 4
var message: String
if temp < 10:
message = "Too cold"
elif temp > 30:
message = "Too hot"
else:
message = "Just right"
print(message)

Output:

Too cold

else if becomes elif. message moves above the if so it exists after it, and the new else makes sure it always has a value before it’s printed.

  • if runs its block when the condition is True; else runs when it’s False.
  • elif adds more branches. Only the first true branch runs, so order matters.
  • Combine conditions with and, or and not, and chain comparisons like 0 < x < 30. Mojo stops evaluating as soon as it knows the answer.
  • Zero, "" and empty lists count as False, so if items: means “if there are any”.
  • a if condition else b picks one of two values. Both must be the same type.
  • A var made inside a block stays in that block. Declare it before the if and set it in every branch.

Next up: while loops, how to repeat code for as long as a condition stays true.

Quick check

1. With var score = 95, what does this print? if score >= 70: print("C") then elif score >= 90: print("A")
2. Which line picks "odd" or "even" correctly in Mojo?
3. You create var msg = "hi" inside an if block and print msg after the block. What happens?
4. What does if not items: check, when items is a List[Int]?