The Mojo ManualXYZ Homework Edition

⇩ Download ▾

1.1 Mojo quickstart

Welcome to Mojo, a systems language for the AI era.

This tutorial offers a quick tour of Mojo language fundamentals by showing you how to build a simple application. You'll get a taste of Mojo's syntax and enough familiarity to read and write basic Mojo code.

It should take about 15-30 minutes if you stop to explore, or less if you work straight through.

Setup

Before starting:

As you work through this tour, look for Takeaways items. They connect new Mojo syntax to concepts you may already know from other languages.

Hello Mojo

Create analyzer.mojo in your favorite IDE or editor.

Add this to analyzer.mojo:

def main():
    print("Temperature Analyzer")
Show output ✓ Verified · Mojo 1.1.0 (8189361e)
Temperature Analyzer

Run it:

mojo analyzer.mojo

Takeaways

Variables and data

Update your file to add temperature data:

def main():
    print("Temperature Analyzer")

    # [Float64] sets the List element type at compile time
    var temps: List[Float64] = [20.5, 22.3, 19.8, 25.1]

    print("Recorded", len(temps), "temperatures")
Show output ✓ Verified · Mojo 1.1.0 (8189361e)
Temperature Analyzer
Recorded 4 temperatures

Loops

Print each temperature. Add to the end of main():

def main():
    # ... existing code ...

    for index in range(len(temps)):  # The range is [0, len(temps))
        print(t"  Day {index + 1}: {temps[index]}°C")

Takeaways

Functions

Add a function above main() to calculate the average temperature:

def calculate_average(temps: List[Float64]) -> Float64:
    # A literal with a decimal component defaults to Float64
    var total = 0.0
    for temp in temps:
        total += temp
    return total / Float64(len(temps))

def main():
    # ... existing code ...

Call the function by adding this to the end of main():

    var avg = calculate_average(temps)
    print(t"Average: {round(avg, 2)}°C")

Takeaways

Conditionals

Classify the average temperature. Add to the end of main():

    if avg > 25.0:
        print("Status: Hot week")
    elif avg > 20.0:
        print("Status: Comfortable week")
    else:
        print("Status: Cool week")

Raise errors

Empty data means no average. Update calculate_average() to handle the error:

def calculate_average(temps: List[Float64]) raises -> Float64:
    if len(temps) == 0:
        raise Error("No temperature data")

    var total = 0.0
    for temp in temps:
        total += temp
    return total / Float64(len(temps))

After updating, your app will no longer compile.

Once calculate_average() can raise, its callers must handle or propagate the error. You do that in the next step.

Handle errors

Wrap failable code in try-except for error handling:

    try:
        var avg = calculate_average(temps)
        print(t"Average: {round(avg, 2)}°C")

        if avg > 25.0:
            print("Status: Hot week")
        elif avg > 20.0:
            print("Status: Comfortable week")
        else:
            print("Status: Cool week")
    except e:
        print("Error:", e)

To test the error, replace temps with []. Confirm that your app errors with "No temperature data".

Takeaways

try:
    operation()
except e:
    handle_error(e)   # Runs if an error occurs
else:
    on_success()      # Runs only if no error occurred
finally:
    cleanup()         # Always runs

Python integration

Mojo integrates with libraries written in other languages. Use Python's NumPy to calculate the standard deviation.

Install NumPy with your package manager:

pixi add numpy

or:

uv pip install numpy

Add these imports at the top of your file:

from std.python import Python
from std.python.numpy import copy_to_numpy_array

Then calculate the standard deviation at the end of the try block in main():

var np = Python.import_module("numpy")
var pytemps = copy_to_numpy_array(temps)
var std_dev = np.std(pytemps)
print("Temperature standard deviation:", std_dev)

Final code

Your complete analyzer.mojo:

from std.python import Python
from std.python.numpy import copy_to_numpy_array


def calculate_average(temps: List[Float64]) raises -> Float64:
    if len(temps) == 0:
        raise Error("No temperature data")

    var total = 0.0
    for temp in temps:
        total += temp
    return total / Float64(len(temps))


def main():
    print("Temperature Analyzer")
    var temps: List[Float64] = [20.5, 22.3, 19.8, 25.1]
    print("Recorded", len(temps), "temperatures")

    for index in range(len(temps)):
        print(t"  Day {index + 1}: {temps[index]}°C")

    try:
        var avg = calculate_average(temps)
        print(t"Average: {round(avg, 2)}°C")

        if avg > 25.0:
            print("Status: Hot week")
        elif avg > 20.0:
            print("Status: Comfortable week")
        else:
            print("Status: Cool week")

        var np = Python.import_module("numpy")
        var pytemps = copy_to_numpy_array(temps)
        var std_dev = np.std(pytemps)
        print("Temperature standard deviation:", std_dev)
    except e:
        print("Error:", e)
Show output ✓ Verified · Mojo 1.1.0 (8189361e)
Temperature Analyzer
Recorded 4 temperatures
  Day 1: 20.5°C
  Day 2: 22.3°C
  Day 3: 19.8°C
  Day 4: 25.1°C
Average: 21.92°C
Status: Comfortable week
Temperature standard deviation: 2.0474068965401093

What you touched

You just used: Mojo variables, lists, loops, functions, conditionals, error handling, and Python integration in one working program.

Your first day? Try these

Use Mojo with AI coding assistants

If you use an AI coding assistant, install the Mojo agent skills to give it up-to-date information about the rapidly evolving language:

npx skills add modular/skills

This installs all Mojo agent skills, including the mojo-syntax skill for the latest nightly language releases.

Keep going

Adapted from the Mojo Manual and the MAX GPU programming guides, part of the Modular Platform repository (github.com/modular/modular), Copyright (c) Modular Inc., licensed under the Apache License v2.0 with LLVM Exceptions. Changes were made: reformatted as an accessible XYZ web edition with build-verified example outputs. Mojo and MAX are trademarks of Modular Inc.; this edition is not affiliated with or endorsed by Modular. License: Apache-2.0 WITH LLVM-exception.

These eBooks are a prerelease and are not yet certified conformant with WCAG 2.1 AA or any other accessibility standard. Every page is built against an automated accessibility gate, and our target for the published editions is WCAG 2.2 Level AA. If something is unusable, please tell us.