Skip to content

Mojo Exercises

Reading code is one thing. Writing it from a blank file is where it sticks. This page has 20 exercises that cover the whole tutorial, from loops and strings to traits, ownership, compile-time code, SIMD and Python. They’re grouped into beginner, intermediate and advanced, and each one links to the lesson it practises.

How to get the most out of them:

  • Try first. Write your own version and run it with mojo run before you open the solution.
  • Read the errors. A compile error is part of the exercise. The compiler errors pages explain the common ones.
  • Compare, don’t copy. Your solution may look different from ours and still be right. If the output matches, you’ve done it.

Every solution below was compiled and run with Mojo 1.2, and the output shown is what it printed.

Print a table of Celsius temperatures from 0 to 40 in steps of 10, with the Fahrenheit value next to each (F = C × 1.8 + 32). Practises Mojo For and Mojo Type Conversion.

Hint: range(0, 41, 10) gives 0, 10, 20, 30, 40. Turn the Int into a Float64 before you multiply.

Show solution
def main():
for c in range(0, 41, 10):
var f = Float64(c) * 1.8 + 32
print(c, "C =", f, "F")

Output:

0 C = 32.0 F
10 C = 50.0 F
20 C = 68.0 F
30 C = 86.0 F
40 C = 104.0 F

Float64(c) converts the loop number, so the result is a float. The 41 as the end is needed because range stops before its end value.

Write a function fizzbuzz(n: Int) -> String that returns "Fizz" for multiples of 3, "Buzz" for multiples of 5, "FizzBuzz" for multiples of both, and the number itself otherwise. Print the results for 1 to 15 on one line, separated by commas. Practises Mojo If…Else and Mojo Return Values.

Hint: check 15 first. Collect the results in a List[String] and use ", ".join(...).

Show solution
def fizzbuzz(n: Int) -> String:
if n % 15 == 0:
return "FizzBuzz"
elif n % 3 == 0:
return "Fizz"
elif n % 5 == 0:
return "Buzz"
return String(n)
def main():
var parts: List[String] = []
for n in range(1, 16):
parts.append(fizzbuzz(n))
print(", ".join(parts))

Output:

1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz

The function has to return a String on every path, so the number is converted with String(n). If you check % 3 before % 15, 15 prints Fizz: order matters in an if/elif chain.

Write count_vowels(text: String) -> Int that counts the letters a, e, i, o and u, in upper or lower case. Test it with "Hello, Mojo" and "rhythm". Practises Mojo Strings.

Hint: for c in text goes through the string one character at a time, and c in "aeiou" checks one character.

Show solution
def count_vowels(text: String) -> Int:
var count = 0
for c in text.lower():
if c in "aeiou":
count += 1
return count
def main():
print(count_vowels("Hello, Mojo"))
print(count_vowels("rhythm"))

Output:

4
0

Lower-casing the text first means you only need to check five letters. Looping over a String gives you one user-visible character (a grapheme) at a time.

Write digit_sum(n: Int) -> Int that adds up the digits of a positive number, so digit_sum(2026) is 2 + 0 + 2 + 6 = 10. Don’t convert the number to a string. Practises Mojo While and Mojo Operators.

Hint: n % 10 is the last digit, and n // 10 removes it.

Show solution
def digit_sum(n: Int) -> Int:
var rest = n
var total = 0
while rest > 0:
total += rest % 10
rest //= 10
return total
def main():
print(digit_sum(2026))
print(digit_sum(99999))

Output:

10
45

The argument n is read-only, so the function makes its own var rest to count down with. The loop ends when every digit has been removed.

Write largest(xs: List[Int]) -> Int that returns the biggest number in a list, without using max on the whole list. Try it with [12, 47, 3, 47, 30]. Practises Mojo Lists.

Hint: start with the first item as your best guess and walk through the rest.

Show solution
def largest(xs: List[Int]) -> Int:
var best = xs[0]
for x in xs:
if x > best:
best = x
return best
def main():
var nums: List[Int] = [12, 47, 3, 47, 30]
print("largest:", largest(nums))

Output:

largest: 47

Mojo has no built-in max(list) like Python, so this loop is the way. It assumes the list isn’t empty: xs[0] on an empty list would stop the program.

Write double_all that doubles every number in the caller’s list, so [1, 2, 3] becomes [2, 4, 6] without making a new list. Practises Mojo Argument Conventions and Mojo For.

Hint: the argument needs mut, and the loop variable needs ref so you can change the items.

Show solution
def double_all(mut xs: List[Int]):
for ref x in xs:
x *= 2
def main():
var nums: List[Int] = [1, 2, 3]
double_all(nums)
print(nums)

Output:

[2, 4, 6]

Without mut, the function only gets a read-only view of the list. Without ref, the loop variable is a read-only value, and x *= 2 doesn’t compile.

Count how often each word appears in "the cat and the dog and the bird" and print each word with its count. Practises Mojo Dictionaries.

Hint: counts.get(w).or_else(0) gives the current count, or 0 for a new word.

Show solution
def main():
var text = "the cat and the dog and the bird"
var counts: Dict[String, Int] = {}
for word in text.split(" "):
var w = String(word)
counts[w] = counts.get(w).or_else(0) + 1
for item in counts.items():
print(item.key, item.value)

Output:

the 3
cat 1
and 2
dog 1
bird 1

get returns an Optional, so a missing word doesn’t raise an error. A Dict keeps keys in the order they were first added, which is why the comes first. Iterating needs item.key and item.value; for k, v in counts.items() doesn’t compile.

You get a list of strings: ["12", "seven", "30", "", "5"]. Add up the ones that are valid whole numbers and count how many you skipped. Practises Mojo Try/Except.

Hint: Int(text) raises on bad input. Catch it inside the loop so one bad value doesn’t stop the rest.

Show solution
def main():
var inputs: List[String] = ["12", "seven", "30", "", "5"]
var total = 0
var skipped = 0
for text in inputs:
try:
total += Int(text)
except:
skipped += 1
print("total:", total, "skipped:", skipped)

Output:

total: 47 skipped: 2

Because the error is handled inside main, main doesn’t need raises. The empty string counts as invalid too.

Make a Rectangle struct with a width and a height (both Float64), methods area() and perimeter(), and make print(r) show Rectangle 3.0 x 4.5. Practises Mojo Structs, Mojo Methods and Mojo Printing Your Types.

Hint: @fieldwise_init writes the initializer. For printing, conform to Writable and write a write_to method.

Show solution
@fieldwise_init
struct Rectangle(Writable):
var width: Float64
var height: Float64
def area(self) -> Float64:
return self.width * self.height
def perimeter(self) -> Float64:
return 2 * (self.width + self.height)
def write_to(self, mut writer: Some[Writer]):
writer.write("Rectangle ", self.width, " x ", self.height)
def main():
var r = Rectangle(3.0, 4.5)
print(r)
print("area:", r.area(), "perimeter:", r.perimeter())

Output:

Rectangle 3.0 x 4.5
area: 13.5 perimeter: 15.0

The methods take plain self because they only read the fields. Without write_to, Writable would print every field as Rectangle(width=3.0, height=4.5).

Make a Vec2 struct with x and y so that a + b adds two vectors, a * 3.0 scales one, and == compares them. Practises Mojo Operator Overloading.

Hint: the methods are __add__, __mul__ and __eq__. == also needs the Equatable trait.

Show solution
@fieldwise_init
struct Vec2(Equatable, ImplicitlyCopyable, Writable):
var x: Float64
var y: Float64
def __add__(self, other: Self) -> Self:
return Vec2(self.x + other.x, self.y + other.y)
def __mul__(self, k: Float64) -> Self:
return Vec2(self.x * k, self.y * k)
def __eq__(self, other: Self) -> Bool:
return self.x == other.x and self.y == other.y
def main():
var a = Vec2(1.0, 2.0)
var b = Vec2(0.5, 0.5)
print(a + b)
print(a * 3.0)
print(a + b == Vec2(1.5, 2.5))

Output:

Vec2(x=1.5, y=2.5)
Vec2(x=3.0, y=6.0)
True

ImplicitlyCopyable makes the small vector copy like a number. Writable with no write_to of its own prints the struct name and every field.

Write a Shape trait with area() and name(), two structs (Circle and Square) that conform to it, and one generic function report that prints any shape. Practises Mojo Traits and Mojo Generics.

Hint: the generic function looks like def report[T: Shape](shape: T):. Use round(x, 2) to keep the circle’s area short.

Show solution
trait Shape:
def area(self) -> Float64:
...
def name(self) -> String:
...
@fieldwise_init
struct Circle(Shape):
var radius: Float64
def area(self) -> Float64:
return 3.14159 * self.radius * self.radius
def name(self) -> String:
return "circle"
@fieldwise_init
struct Square(Shape):
var side: Float64
def area(self) -> Float64:
return self.side * self.side
def name(self) -> String:
return "square"
def report[T: Shape](shape: T):
print("a", shape.name(), "with area", round(shape.area(), 2))
def main():
report(Circle(2.0))
report(Square(3.0))

Output:

a circle with area 12.57
a square with area 9.0

The ... body in the trait means “every conforming struct must write this”. Mojo builds a separate copy of report for each type at compile time.

Make an Account struct with a balance and a withdraw(amount) method. If the amount is more than the balance, raise a custom error InsufficientFunds that says how much money is missing. Practises Mojo Custom Errors.

Hint: declare the error type in the signature: def withdraw(mut self, amount: Int) raises InsufficientFunds:. In the except e: block, e has that type, so you can read its fields.

Show solution
@fieldwise_init
struct InsufficientFunds(Writable):
var needed: Int
struct Account:
var balance: Int
def __init__(out self, balance: Int):
self.balance = balance
def withdraw(mut self, amount: Int) raises InsufficientFunds:
if amount > self.balance:
raise InsufficientFunds(amount - self.balance)
self.balance -= amount
def main():
var acc = Account(100)
try:
acc.withdraw(30)
print("balance:", acc.balance)
acc.withdraw(200)
print("balance:", acc.balance)
except e:
print("not enough money, short by", e.needed)

Output:

balance: 70
not enough money, short by 130

The second withdraw raises before it changes anything, so the second print never runs. A typed error carries data (needed), which a plain Error("...") message can’t do as cleanly.

Write winner(a, b) that returns "player 1", "player 2" or "draw" for two moves. Use a match on the pair of moves. Practises Mojo Match.

Hint: match a tuple: match (a, b):. One case can list several patterns with |.

Show solution
def winner(a: String, b: String) -> String:
if a == b:
return "draw"
match (a, b):
case ("rock", "scissors") | ("scissors", "paper") | ("paper", "rock"):
return "player 1"
case _:
return "player 2"
def main():
print(winner("rock", "scissors"))
print(winner("rock", "paper"))
print(winner("paper", "paper"))

Output:

player 1
player 2
draw

Once draws are handled, there are only three winning pairs for player 1, so case _ can cover everything else.

Predict what this program prints, then run it. Practises Mojo Value Semantics and Mojo Moving Values.

def make_list() -> List[Int]:
var xs: List[Int] = [0, 0, 0]
return xs^
def main():
var a = make_list()
var b = a.copy()
b[0] = 9
var c = a^
print(b, c)

Hint: .copy() makes an independent list. ^ moves the list, so a can’t be used afterwards.

Show solution
def make_list() -> List[Int]:
var xs: List[Int] = [0, 0, 0]
return xs^
def main():
var a = make_list()
var b = a.copy()
b[0] = 9
var c = a^
print(b, c)

Output:

[9, 0, 0] [0, 0, 0]

Changing b doesn’t touch a, because b is a real copy. Then a^ hands the list to c without copying. Add print(a) at the end and Mojo refuses to build it: “use of uninitialized value ‘a’”.

Write one generic function count_matches that counts how often a value appears in a list, and works for both List[Int] and List[String]. Practises Mojo Generics and Mojo Common Traits.

Hint: the element type only needs to support ==, which is the Equatable trait.

Show solution
def count_matches[T: Equatable](items: List[T], target: T) -> Int:
var n = 0
for item in items:
if item == target:
n += 1
return n
def main():
var nums: List[Int] = [1, 2, 2, 3, 2]
var words: List[String] = ["hi", "yo", "hi"]
print(count_matches(nums, 2))
print(count_matches(words, "hi"))

Output:

3
2

T: Equatable says “any type that can be compared with ==”. Mojo infers T from the arguments, so you don’t write count_matches[Int](...).

Write power[n: Int](x: Float64) -> Float64 where the exponent is a compile-time parameter, and use comptime for so the loop is unrolled when the program is built. Practises Mojo Parameters and Mojo Compile-Time If & Loops.

Hint: inside the function, comptime for _ in range(n): repeats the body n times in the compiled code.

Show solution
def power[n: Int](x: Float64) -> Float64:
var result = 1.0
comptime for _ in range(n):
result *= x
return result
def main():
print(power[3](2.0))
print(power[10](1.5))
print(power[0](7.0))

Output:

8.0
57.6650390625
1.0

Each different n creates its own version of the function. power[3] becomes three multiplications in a row, with no loop counter left at run time.

Write a dot function that takes two SIMD[DType.float32, 4] vectors and returns their dot product (multiply matching items, then add them all up). Practises Mojo SIMD.

Hint: a * b multiplies all four pairs at once. A SIMD vector has a method that adds up its items.

Show solution
def dot(a: SIMD[DType.float32, 4], b: SIMD[DType.float32, 4]) -> Float32:
return (a * b).reduce_add()
def main():
var a = SIMD[DType.float32, 4](1, 2, 3, 4)
var b = SIMD[DType.float32, 4](10, 20, 30, 40)
print(a * b)
print(dot(a, b))

Output:

[10.0, 40.0, 90.0, 160.0]
300.0

reduce_add() sums the four lanes: 10 + 40 + 90 + 160 = 300. The return type is Float32, a single value of the same element type.

Make a Resource struct that prints open <name> when it’s created and close <name> when it’s destroyed. Create A and B, move A into a function use, and print something after the call. Predict the order of the lines first. Practises Mojo Destructors and Mojo Value Lifecycle.

Hint: the destructor is def __deinit__(deinit self):. A value is destroyed right after its last use, not at the end of the block.

Show solution
struct Resource:
var name: String
def __init__(out self, name: String):
self.name = name
print("open", self.name)
def __deinit__(deinit self):
print("close", self.name)
def use(var r: Resource):
print("using", r.name)
def main():
var a = Resource("A")
var b = Resource("B")
use(a^)
print("back in main")
print("b is", b.name)

Output:

open A
open B
using A
close A
back in main
b is B
close B

use owns A after the move, so A is closed inside use, before main carries on. B is closed right after its last use, the final print.

Use Python’s json module from Mojo to read {"name": "Ada", "langs": ["mojo", "python"], "year": 1815}, then get the name as a Mojo String and the year as a Mojo Int. Practises Mojo Calling Python and Mojo Python Types.

Hint: Python.import_module("json") gives you the module. Convert back with String(py=...) and Int(py=...).

Show solution
from std.python import Python
def main() raises:
var json = Python.import_module("json")
var data = json.loads('{"name": "Ada", "langs": ["mojo", "python"], "year": 1815}')
var name = String(py=data["name"])
var year = Int(py=data["year"])
print(name, "was born in", year)
print("languages:", len(data["langs"]))

Output:

Ada was born in 1815
languages: 2

Everything that comes from Python is a PythonObject, and any call into Python can raise, so main needs raises. Once you’ve converted a value, it’s an ordinary Mojo value again.

This function splits total items into chunks of size. A size of 0 would divide by zero. Add a constraint so that chunk_count[0](10) doesn’t even compile, while chunk_count[4](10) still works. Practises Mojo Constraints.

def chunk_count[size: Int](total: Int) -> Int:
return (total + size - 1) // size

Hint: a where clause goes after the return type.

Show solution
def chunk_count[size: Int](total: Int) -> Int where size > 0:
return (total + size - 1) // size
def main():
print(chunk_count[4](10))
print(chunk_count[5](10))

Output:

3
2

And with a size of 0:

def chunk_count[size: Int](total: Int) -> Int where size > 0:
return (total + size - 1) // size
def main():
print(chunk_count[0](10))
chunks.mojo:6:11: error: invalid call to 'chunk_count': violated constraint
print(chunk_count[0](10))
^~~~~~~~~~~
chunks.mojo:1:53: note: constraint declared here evaluated to False, expected '(size > Int(0))'
def chunk_count[size: Int](total: Int) -> Int where size > 0:
^
chunks.mojo:1:5: note: function declared here
def chunk_count[size: Int](total: Int) -> Int where size > 0:
^
mojo: error: failed to parse the provided Mojo source module

The mistake is caught while building, at the line that made it. The program never runs, so the division by zero can’t happen.

  • Beginner exercises practise loops, if/elif, strings, // and %, lists and mut/ref.
  • Intermediate exercises add dictionaries, try/except, structs, operators, traits, custom errors, match and moves.
  • Advanced exercises cover generics, compile-time parameters, SIMD, destructors, Python interop and where constraints.
  • If one felt hard, reread the linked lesson and try again a day later. That’s how it sticks.

Next up: interview questions, short questions and answers that check you can explain Mojo, not just write it.

Quick check

1. In exercise 6, why does the loop use for ref x in xs instead of for x in xs?
2. In exercise 18, when is resource B closed?
3. What does where size > 0 do in exercise 20?