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.
A basic if
Section titled “A basic if”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: 15The 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 !=.
Adding else
Section titled “Adding else”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.
More choices with elif
Section titled “More choices with elif”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: B84 >= 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.
Combining conditions
Section titled “Combining conditions”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.andisTrueonly when both sides areTrue.orisTruewhen at least one side isTrue.notflipsTruetoFalseand 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.Mojo stops as soon as it knows the answer
Section titled “Mojo stops as soon as it knows the answer”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.
Empty and zero count as False
Section titled “Empty and zero count as False”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 oddPeople 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 modulePython 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.
Variables made inside an if stay inside
Section titled “Variables made inside an if stay inside”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 moduleThe 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 managerThat’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.)
Common mistakes
Section titled “Common mistakes”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 moduleWriting 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 moduleIn 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").
Practice
Section titled “Practice”1. Even or odd
Section titled “1. Even or odd”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 evenThe conditional expression picks "even" or "odd" in one line, and print puts spaces between its values.
2. Ticket price
Section titled “2. Ticket price”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: 10price 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.
3. Fix the program
Section titled “3. Fix the program”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 coldelse 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.
ifruns its block when the condition isTrue;elseruns when it’sFalse.elifadds more branches. Only the first true branch runs, so order matters.- Combine conditions with
and,orandnot, and chain comparisons like0 < x < 30. Mojo stops evaluating as soon as it knows the answer. - Zero,
""and empty lists count asFalse, soif items:means “if there are any”. a if condition else bpicks one of two values. Both must be the same type.- A
varmade inside a block stays in that block. Declare it before theifand set it in every branch.
Next up: while loops, how to repeat code for as long as a condition stays true.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Control flow in the Mojo manual: the official guide to
if, conditional expressions, loops andmatch. - Compound statements reference: the exact rules for
if,elif,elseand block scopes. - Basics cheat sheet: a one-page summary, with
ifand the conditional expression side by side. - Ternary conditional in the expressions reference: the rules for
a if condition else b, including how chained ones are grouped.