Login
📚 The Mojo Manual
Chapters ▾
⇩ Download ▾

1.1 Mojo quickstart

This page quickly teaches you Mojo's syntax by focusing on code.

For more explanation of the language features, see the Mojo get started tutorial or Mojo language basics.

Project setup

You can install Mojo using any Python or Conda package manager, but we recommend either pixi or uv.

Use the following command to install the:

uv

  1. If needed, install uv:

    curl -LsSf https://astral.sh/uv/install.sh | sh
  2. Create a project and install Mojo:

    uv init temperature-analyzer && cd temperature-analyzer
    uv venv && source .venv/bin/activate
    uv add mojo --prerelease allow

    Note that the --prerelease allow flag is required only when installing beta (or dev) builds.

pixi

  1. If needed, install pixi:

    curl -fsSL https://pixi.sh/install.sh | sh
  2. Create a project and install Mojo:

    pixi init temperature-analyzer \
        -c https://conda.modular.com/max/  -c conda-forge
    cd temperature-analyzer
    pixi add mojo
    pixi shell

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.0.0b2 (2cf4d08a)
Temperature Analyzer

Run it:

mojo analyzer.mojo

Insights:

Variables and data

Update your file to add temperature data:

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

    # Square brackets tell Mojo the `List` 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.0.0b2 (2cf4d08a)
Temperature Analyzer
Recorded 4 temperatures

Loops

Print each temperature. Add to main under the print statement:

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

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

Insights:

Functions

Add this function above main to calculate the average temperature:

def calculate_average(temps: List[Float64]) -> Float64:
    var total: Float64 = 0.0
    for index in range(len(temps)):
        total += temps[index]
    return total / Float64(len(temps))

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

Add to the end of main to call the function:

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

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

Handle empty data by updating calculate_average. Now the function can raise an error.

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

    var total: Float64 = 0.0
    for index in range(len(temps)):
        total += temps[index]
    return total / Float64(len(temps))

What changed:

Handle errors

In main, wrap your code in try-except for error handling:

    try:
        var avg = calculate_average(temps)
        print(t"Average: {avg}°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 List[Float64]. Confirm that your app errors with "No temperature data".

Python integration

Add statistics with Python's numpy. First, install it:

uv

uv pip install numpy

pixi

pixi add numpy

pip

pip install numpy

conda

conda install numpy

Then, add the following imports at the top of your file:

from std.python import Python, PythonObject

Now, calculate Python stats at the end of the try block in main:

        var np = Python.import_module("numpy")
        var pytemps: PythonObject = [20.5, 22.3, 19.8, 25.1]
        print("Temperature standard deviation:", np.std(pytemps))

Final code

Your complete analyzer.mojo:

from std.python import Python, PythonObject

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

    var total: Float64 = 0.0
    for index in range(len(temps)):
        total += temps[index]
    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: {avg}°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: PythonObject = [20.5, 22.3, 19.8, 25.1]
        print("Temperature standard deviation:", np.std(pytemps))
        _ = pytemps^ # Allow the Python object to deallocate
    except e:
        print("Error:", e)
Show output ✓ Verified · Mojo 1.0.0b2 (2cf4d08a)
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.924999999999997°C
Status: Comfortable week
Error: No module named 'numpy'

What you touched

Mojo variables, lists, loops, functions, conditionals, error handling, and Python integration, all in one working program.

Use Mojo with AI coding assistants

If you use AI coding assistants, the mojo-syntax skill keeps you aligned with the latest nightly language releases. Stay up to date with Mojo's rapid development:

npx skills add modular/skills

This installs all four Mojo agent skills, including mojo-syntax.

Keep going

Build something bigger: Tutorial: Game of Life Language guide: Mojo Manual API docs: Standard Library