Mojo Booleans
A boolean is a value that’s either true or false. It’s the smallest type there is, but every decision your program makes (every if, every loop that stops) comes down to one. In Mojo the type is called Bool, and it works almost exactly like Python’s bool.
True and False
Section titled “True and False”A Bool has two possible values, True and False, with a capital first letter:
def main(): var is_open = True var has_ticket: Bool = False print(is_open, has_ticket)Output:
True FalseMojo is case-sensitive, so true (lowercase, as in C, Java or JavaScript) doesn’t exist:
def main(): var on = true print(on)hello.mojo:2:14: error: use of unknown declaration 'true' var on = true ^~~~mojo: error: failed to parse the provided Mojo source moduleComparisons give you a Bool
Section titled “Comparisons give you a Bool”You’ll rarely type True or False yourself. Most booleans come from comparisons:
def main(): var age = 20 var is_adult = age >= 18 print(is_adult) print(age == 20, age != 20) print(age < 13, age > 65)Output:
TrueTrue FalseFalse Falseage >= 18 asks a question, and the answer is a Bool. You can store it in a variable (like is_adult) to give the question a name, which often makes code easier to read. All the comparison operators (==, !=, <, <=, >, >=) are covered in Mojo Operators.
Combining with and, or and not
Section titled “Combining with and, or and not”Mojo uses words for boolean logic, the same as Python:
| Operator | Result is True when… |
Example |
|---|---|---|
a and b |
both are true | has_ticket and is_adult |
a or b |
at least one is true | is_weekend or is_holiday |
not a |
a is false |
not is_open |
def main(): var age = 20 var has_ticket = True var is_vip = False print(age >= 18 and has_ticket) print(has_ticket or is_vip) print(not is_vip) print(age >= 18 and (has_ticket or is_vip))Output:
TrueTrueTrueTruenot is applied first, then and, then or. When you mix and and or, add parentheses like in the last line. They make your intent clear and cost nothing.
If you’re coming from C, Java or JavaScript, &&, || and ! don’t work in Mojo. a > 1 && a < 5 is a syntax error (unexpected token in expression).
Short-circuiting
Section titled “Short-circuiting”and and or stop as soon as they know the answer:
False and anythingis alwaysFalse, so the right side isn’t run.True or anythingis alwaysTrue, so the right side isn’t run.
You can see this with a function that prints when it’s called:
def check(label: String) -> Bool: print("checking", label) return True
def main(): var ready = False var done = True print(ready and check("A")) print(done or check("B")) print(done and check("C"))Output:
FalseTruechecking CTrueOnly check("C") ran. This is useful when the right side would be slow, or would fail if the left side wasn’t true. For example: count > 0 and total / count > 10 only divides when count isn’t zero.
Truthiness: values that act like True or False
Section titled “Truthiness: values that act like True or False”Many values can be used where a Bool is expected. Like in Python, “empty” or “zero” values count as false, and everything else counts as true. You can check with Bool(...):
def main(): var empty_list: List[Int] = [] print(Bool(0), Bool(42)) print(Bool(0.0), Bool(-1.5)) print(Bool(""), Bool("hi")) print(Bool(empty_list))Output:
False TrueFalse TrueFalse TrueFalseCounts as False |
Counts as True |
|---|---|
0, 0.0 |
any other number |
"" (empty string) |
any non-empty string, even " " |
| an empty list, dict or set | a collection with items in it |
None (in an Optional) |
an Optional that holds a value |
That’s why you can write if name: or if not name: directly:
def main(): var name = "" if not name: print("Please enter your name.") var shown = name or "guest" print("Hello,", shown)Output:
Please enter your name.Hello, guestname or "guest" works like in Python: if name is empty, you get "guest" instead. It’s a short way to pick a default. (This needs both sides to be the same type, here both strings.)
Bool and numbers
Section titled “Bool and numbers”Bool is its own type, not a number. You can turn it into one with Int(...), which gives 1 for True and 0 for False:
def main(): var passed_a = True var passed_b = False var passed_c = True var count = Int(passed_a) + Int(passed_b) + Int(passed_c) print(count, "tests passed")Output:
2 tests passedIn Python, True + 1 is 2, because bool is a kind of int. In Mojo that’s an error ('Bool' does not implement the '__add__' method), so convert with Int(...) first. The Bool API docs list everything else a Bool can do.
Practice
Section titled “Practice”1. Can I go in?
Section titled “1. Can I go in?”A club lets you in if you’re at least 18 and have a ticket, or if you’re on the guest list. Write it with age = 16, has_ticket = True and on_guest_list = True, and print the result.
Hint: use parentheses around the and part.
Show solution
def main(): var age = 16 var has_ticket = True var on_guest_list = True var can_enter = (age >= 18 and has_ticket) or on_guest_list print("Can enter:", can_enter)Output:
Can enter: TrueThe first part is False (16 is under 18), but on_guest_list is True, so or gives True.
2. Safe average
Section titled “2. Safe average”Write a program with total = 50 and count = 0. Print True if the average (total // count) is above 10, but make sure you never divide when count is 0. Then change count to 4 and run it again.
Hint: put count > 0 first and join it with and.
Show solution
def main(): var total = 50 var count = 0 print(count > 0 and total // count > 10) count = 4 print(count > 0 and total // count > 10)Output:
FalseTrueWhen count is 0, count > 0 is False, so and stops and the division never runs. With count = 4, the average is 12, which is above 10.
- A
BoolisTrueorFalse, with a capital letter. - Comparisons like
age >= 18produce aBool. - Combine with the words
and,or,not(not&&,||,!). Use parentheses when you mix them. andandorshort-circuit: the right side only runs when it’s needed.- Zero, empty strings and empty collections count as false; most other values count as true.
Boolisn’t a number: useInt(flag)to get1or0.
Next up: operators, all the symbols for math, comparing and working with bits.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Mojo manual: Operators: the boolean logic, short-circuit and truthiness sections.
- Mojo manual: Types: the official introduction to
Bool. BoolAPI docs: every method and trait of theBooltype.- Operator reference: the precedence table, including
not,andandor.