Mojo Syntax
Syntax is the set of rules for how code has to be written so the compiler understands it. Mojo’s syntax is close to Python’s, so if you’ve written Python, most of this page will feel familiar. There are a few differences, though, and they’re exactly the ones that trip people up. We’ll point them out as we go.
The shape of a Mojo program
Section titled “The shape of a Mojo program”Here’s a small but complete program:
def main(): var temperature = 30 if temperature > 25: print("It is hot.") print("Drink water.") print("Done.")Output:
It is hot.Drink water.Done.Let’s go through the rules this tiny program already follows:
- The program starts at
def main():. Every Mojo program needs amainfunction. var temperature = 30creates a variable. In Mojo, a new variable needsvarin front of it.if temperature > 25:ends with a colon, and the lines that belong to it are indented further.- Statements run from top to bottom, one per line. No semicolons needed.
Indentation makes blocks
Section titled “Indentation makes blocks”A line that ends with a colon (:) starts a block: the body of a function, an if, a loop and so on. Everything indented under it belongs to that block. When the indentation goes back, the block is over.
In the program above:
print("It is hot.")andprint("Drink water.")are indented under theif, so they only run when it’s hot.print("Done.")is back at the level ofif, so it always runs.
Use 4 spaces per level. That’s what the official docs and mojo format use. You can’t leave a block empty, and you can’t forget to indent:
def main():print("Hello")hello.mojo:2:1: error: expressions must not appear at file scope; move this into a function bodyprint("Hello")^hello.mojo:1:12: error: body must not be empty; use 'pass' or check that the lines below are indenteddef main(): ^mojo: error: failed to parse the provided Mojo source moduleMojo is telling you two things: print isn’t inside any function, and main has an empty body. Indent the print line and both errors go away.
New variables need var
Section titled “New variables need var”This is the biggest difference from Python. In Python you can write x = 5 to create a variable. In Mojo, that’s an error:
def main(): x = 5 print(x)hello.mojo:2:5: error: implicit declaration of 'x' is not allowed; add 'var' to declare a new name x = 5 ^ varmojo: error: failed to parse the provided Mojo source moduleThe error even shows the fix. Write var the first time you create a variable, and leave it out when you change it later:
def main(): var x = 5 x = x + 1 print(x)Output:
6You’ll learn all about variables in the Variables lesson. For now, just remember: new name, use var.
Mojo is case-sensitive
Section titled “Mojo is case-sensitive”Upper and lower case letters are different. print works, but Print doesn’t exist:
def main(): Print("hi")hello.mojo:2:5: error: use of unknown declaration 'Print' Print("hi") ^~~~~mojo: error: failed to parse the provided Mojo source moduleThe same goes for your own names: score, Score and SCORE are three different things.
Naming things
Section titled “Naming things”Names (for variables, functions and so on) can use ASCII letters, digits and underscores, and can’t start with a digit. Mojo code follows two simple conventions:
| What | Style | Examples |
|---|---|---|
| Variables and functions | lower_snake_case |
count, max_value, print_report |
| Types (like structs) | PascalCase |
String, List, Point |
The compiler doesn’t force these, but every Mojo library uses them, so your code will look normal to other Mojo developers.
One statement per line, usually
Section titled “One statement per line, usually”You don’t end lines with a semicolon. If you really want two short statements on one line, a semicolon can join them:
def main(): var a = 1; var b = 2 print(a + b)Output:
3It works, but most code keeps one statement per line because it’s easier to read.
Long lines
Section titled “Long lines”When a line gets too long, wrap it in parentheses and split it over several lines. Inside parentheses, Mojo knows the statement isn’t finished yet:
def main(): var total = ( 100 + 250 + 75 ) print(total)Output:
425The official lexical structure reference lists the other ways to continue a line (like a backslash at the end), but parentheses are the clearest and the one the docs recommend.
Functions can come in any order
Section titled “Functions can come in any order”You can write helper functions above or below main. Mojo reads the whole file first, so the order doesn’t matter:
def main(): greet()
def greet(): print("Hi there!")Output:
Hi there!Most people put main at the bottom or the top and stick with it. Functions get their own lesson later.
Importing things
Section titled “Importing things”The basics you’ve seen so far (print, numbers, strings, lists) are always available. Anything else comes from the standard library, and you bring it in with from ... import ... at the top of the file:
from std.math import sqrt
def main(): print(sqrt(16.0))Output:
4.0Standard library modules start with std., like std.math here. You’ll meet more of them as you go.
Coming from Python?
Section titled “Coming from Python?”A quick list of what’s the same and what’s different, so far:
| Python | Mojo | |
|---|---|---|
| Blocks | Indentation and : |
Same |
| Functions | def |
Same |
| New variable | x = 5 |
var x = 5 |
| Code at the top level of a file | Runs when the file runs | Not allowed: code goes inside functions |
| Where the program starts | The first line of the file | def main(): |
The official tips for Python developers go further, once you’ve learned a bit more.
Practice
Section titled “Practice”1. Fix the program
Section titled “1. Fix the program”This program has two mistakes. Find them and fix them so it prints Total: 12.
def main(): price = 4 var count = 3 Print("Total:", price * count)Hint: run it and read the first error. Then run it again.
Show solution
def main(): var price = 4 var count = 3 print("Total:", price * count)Output:
Total: 12price is a new variable, so it needs var. And Print must be print, because Mojo is case-sensitive.
2. A block inside a block
Section titled “2. A block inside a block”Write a program with a variable score = 85. If the score is above 50, print You passed. and, inside that same block, print Well done. After the if (not inside it), print Thanks for playing.
Hint: the two lines inside the if need one more level of indentation than the if itself.
Show solution
def main(): var score = 85 if score > 50: print("You passed.") print("Well done.") print("Thanks for playing.")Output:
You passed.Well done.Thanks for playing.Change score to 30 and run it again: only Thanks for playing. is printed, because the indented lines belong to the if.
- Every program starts at
def main():, and code lives inside functions. - A line ending in
:starts a block; the block is everything indented under it (4 spaces per level). - A new variable needs
var:var x = 5. Changing it later doesn’t. - Mojo is case-sensitive:
printandPrintare different. - Use
lower_snake_casefor variables and functions,PascalCasefor types. - Wrap long expressions in parentheses to split them over several lines.
- Bring in standard library code with
from std.module import name.
Next up: comments, how to leave notes in your code for people (including future you).
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Mojo language basics: the official overview of the language.
- Lexical structure reference: the exact rules for lines, indentation, semicolons and line continuation.
- Basics cheat sheet: a one-page summary of Mojo syntax, handy to keep open.
- Keywords reference: every reserved word, and the rules for names.
- Mojo tips for Python developers: where Python habits work in Mojo and where they don’t.