Mojo Operators
Operators are the symbols that do something with values: + adds, < compares, and combines. Mojo copies Python’s operators almost one for one, so most of this page will look familiar. There’s one important difference with division, though, and it can quietly give you wrong answers. We’ll start there right after the basics.
Math operators
Section titled “Math operators”| Operator | Meaning | Example | Result |
|---|---|---|---|
+ |
Add | 7 + 3 |
10 |
- |
Subtract | 7 - 3 |
4 |
* |
Multiply | 7 * 3 |
21 |
/ |
Divide | 7.0 / 2.0 |
3.5 |
// |
Floor divide (round down) | 7 // 2 |
3 |
% |
Remainder | 7 % 2 |
1 |
** |
Power | 2 ** 8 |
256 |
def main(): var a = 7 var b = 3 print(a + b, a - b, a * b) print(a // b, a % b, a ** b)Output:
10 4 212 1 343-x flips the sign of a number. ** is the power operator; the caret ^ is not power in Mojo (it’s bitwise XOR, see below).
Division: / on two Int variables gives an Int
Section titled “Division: / on two Int variables gives an Int”This is the one to remember. In Python 3, / always gives a decimal: 7 / 2 is 3.5. In Mojo, when both sides are Int variables, / stays in whole numbers and drops the fraction:
def main(): var total = 7 var people = 2 print(total / people)Output:
3No error, no warning, just 3. The type of total / people is Int, because / keeps the type of its operands, and the result is cut toward zero.
To confuse things more, literals behave differently. Numbers you type straight into the code are worked out by the compiler, which isn’t limited to Int:
def main(): print(7 / 2) var share = 7 / 2 print(share)Output:
3.53.5So the same 7 / 2 gives 3.5 with literals and 3 with Int variables. When you want a decimal answer from whole-number variables, convert them to Float64 first:
def main(): var total = 7 var people = 2 print(Float64(total) / Float64(people))Output:
3.5/, // and % with negative numbers
Section titled “/, // and % with negative numbers”For Int values, / and // only differ when the answer is negative:
/cuts toward zero:-7 / 2is-3.//rounds down (toward minus infinity):-7 // 2is-4, the same as in Python.
def main(): var a = -7 var b = 2 print(a / b) print(a // b) print(a % b)Output:
-3-41% matches //, just like Python: a == b * (a // b) + a % b is always true, so -7 % 2 is 1. On floats, / is normal division and // rounds down to a whole number that’s still a float (7.0 // 2.0 is 3.0). The Mojo manual’s page on operators explains these rules in its “Division and remainder” section.
Comparison operators
Section titled “Comparison operators”Comparisons ask a question and give back a Bool:
| Operator | Meaning |
|---|---|
== |
equal to |
!= |
not equal to |
<, <= |
less than, less than or equal |
>, >= |
greater than, greater than or equal |
def main(): var x = 5 print(x == 5, x != 5) print(x < 10, x >= 6) print(1 < x < 10) print(1 < x < 3)Output:
True FalseTrue FalseTrueFalseLike Python, you can chain comparisons: 1 < x < 10 means 1 < x and x < 10. It reads like math and works with any of these operators. Remember from Mojo Numbers not to use == on decimal results; use isclose instead.
Logical operators
Section titled “Logical operators”and, or and not combine booleans: age >= 18 and has_id. They’re words, not symbols (&& and || don’t work). The Mojo Booleans lesson covers them in detail, including short-circuiting.
Assignment operators
Section titled “Assignment operators”= stores a value. The augmented forms change a variable using its current value:
| Short form | Means |
|---|---|
x += 5 |
x = x + 5 |
x -= 5 |
x = x - 5 |
x *= 5 |
x = x * 5 |
x /= 5 |
x = x / 5 |
x //= 5 |
x = x // 5 |
x %= 5 |
x = x % 5 |
x **= 2 |
x = x ** 2 |
def main(): var points = 10 points += 5 print(points) points *= 2 print(points) points /= 4 print(points)Output:
15307The same division rule applies: points is an Int, so 30 / 4 gives 7, not 7.5.
There’s no ++ or --. count++ gives a confusing error ('None' does not implement the '__pos__' method); write count += 1 instead.
Bitwise operators
Section titled “Bitwise operators”These work on the individual bits of integers. You’ll need them for flags, colors, file formats and low-level code. bin() shows a number in binary, which helps to see what happens:
| Operator | Name | Keeps a bit when… |
|---|---|---|
& |
AND | it’s 1 in both |
| |
OR | it’s 1 in either |
^ |
XOR | it’s 1 in exactly one |
~ |
NOT | (flips every bit) |
<< |
Left shift | (moves bits left) |
>> |
Right shift | (moves bits right) |
def main(): var flags: UInt8 = 0b0101 var mask: UInt8 = 0b0011 print(bin(flags & mask), bin(flags | mask), bin(flags ^ mask)) print(~flags) print(1 << 4, 64 >> 2)Output:
0b1 0b111 0b11025016 160b0101 & 0b0011keeps only the bit that’s set in both:0b1.~flagsflips all 8 bits of theUInt8:00000101becomes11111010, which is250.1 << 4is 1 times 2 four times (16);64 >> 2is 64 halved twice (16).
Shifting by as many bits as the type has, or more, has no defined result, so don’t do it.
Other operators you’ll meet
Section titled “Other operators you’ll meet”def main(): var score = 72 var result = "pass" if score >= 50 else "fail" print(result) var colors: List[String] = ["red", "green"] print("red" in colors, "blue" not in colors) print("oj" in "Mojo")Output:
passTrue TrueTruea if condition else bis a conditional expression: one value or the other, in a single line. There’s no? :like in C.inandnot incheck whether a collection holds a value, or a string holds some text.
Operator precedence
Section titled “Operator precedence”When an expression has several operators, some go first. From first to last, the main ones are: **, then -x and ~x, then *, /, //, %, then + and -, then shifts, then &, ^, |, then comparisons, then not, and, or.
def main(): print(2 + 3 * 4) print((2 + 3) * 4) print(-2 ** 2) print(2 ** 3 ** 2)Output:
1420-4512-2 ** 2 is -(2 ** 2), and ** groups from the right, so 2 ** 3 ** 2 is 2 ** 9. Both match Python. When you’re not sure, add parentheses: they cost nothing and make your intent clear. The full table is in the operator reference.
Practice
Section titled “Practice”1. Fix the average
Section titled “1. Fix the average”This program should print Average: 2.5, but it prints Average: 2. Fix it.
def main(): var total = 10 var count = 4 print("Average:", total / count)Hint: both variables are Int, so / drops the fraction.
Show solution
def main(): var total = 10 var count = 4 print("Average:", Float64(total) / Float64(count))Output:
Average: 2.5Converting both sides to Float64 makes / do decimal division.
2. Minutes and seconds
Section titled “2. Minutes and seconds”Turn var total_seconds = 135 into minutes and seconds, and print 2 minutes 15 seconds.
Hint: // gives the whole minutes, % gives what’s left.
Show solution
def main(): var total_seconds = 135 var minutes = total_seconds // 60 var seconds = total_seconds % 60 print(minutes, "minutes", seconds, "seconds")Output:
2 minutes 15 seconds135 // 60 is 2 and 135 % 60 is 15. Using // here makes it clear you want whole-number division.
3. Turn a flag on
Section titled “3. Turn a flag on”A settings byte starts at 0b0001. Turn on bit 2 (value 0b0100) with |=, then print the result in binary and as a number.
Hint: use a UInt8 and bin(...).
Show solution
def main(): var settings: UInt8 = 0b0001 settings |= 0b0100 print(bin(settings), settings)Output:
0b101 5OR keeps every bit that’s set in either value, so the old bit stays on and the new one is added.
- Math:
+ - * / // % **. Power is**, not^. /on twoIntvariables gives anIntand drops the fraction (7 / 2with variables is3). Literals like7 / 2give3.5.- For a decimal result, convert first:
Float64(a) / Float64(b). For whole-number division, say so with//. //and%round down, like Python;/onIntcuts toward zero.- Comparisons give a
Booland can be chained (1 < x < 10). Logic usesand,or,not. - Augmented assignment (
+=,-=, …) works; there’s no++. - Bitwise:
& | ^ ~ << >>, best used on sized types likeUInt8.
Next up: type conversion, how to turn numbers into other numbers and strings into numbers (and back).
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Mojo manual: Operators: arithmetic, division rules, comparisons, bitwise and boolean operators, with examples.
- Operator reference: the full precedence and associativity table.
- Types and literals cheat sheet: the short version of the division and overflow rules.
SIMDAPI docs: the methods behind every number operator (__add__,__truediv__,__floordiv__…).