Language basics
26 steps in 6 sets of Mojo.
Mojo reads like Python and compiles like a systems language, and this tour stays on the half that feels familiar. You type variables, typed function signatures, branches, loops, lists, dictionaries, strings, and error handling — the vocabulary every later tour builds on.
The resemblance to Python is real but not total. Every function is a def, a function that can fail has to say raises in its signature, string lists want an explicit type, and there is no negative indexing. Typing these lines out is the fastest way to feel where the two languages part company.
Variables & functions
- Hello from MojoThe smallest complete Mojo program - an entry point and a print.
- Variables and typesTyped bindings, and what reassigning them looks like.
- Defining functionsEvery Mojo function is a
defwith typed arguments. - Default and keyword argumentsDefaults let one function cover several call shapes.
- Converting between typesMojo converts with constructors rather than casts.
- Functions that raiseA
defcannot raise unless its signature says so.
Flow control
- if, elif, and elseBranching that reads exactly like Python.
- while loopsA Collatz walk: loop until the condition finally gives way.
- for and range
rangedrives counted loops with one, two, or three arguments. - break and continueTwo ways to change a loop's mind partway through.
- Conditional expressions
a if cond else bpicks a value without opening a block.
Collections
- List literalsSquare brackets build a
List, and the element type follows. - Growing and shrinking a list
append,insert, andpopcover most list edits. - DictionariesKey-value storage with a declared key type and value type.
- Iterating a dictionary
items()yields entries that carry both halves of the pair. - Searching a listA membership test and a hand-rolled index scan.
- Optional values
Optionalmodels a result that may not be there at all.
Strings
- Building strings
+joins strings, andString()brings other types along. - String methodsTrimming and case conversion ship with the standard
String. - Joining strings
joinglues a list of strings together with a separator. - Searching inside a stringFour ways to ask whether, or where, some text appears.
- Bytes versus charactersA
Stringholds UTF-8, so length depends on what you count.
Errors
- Raising errors
raise Error(...)rejects input a function cannot honor. - try and exceptCatching an error keeps the program running.
- Recovering from an errorA raising helper wrapped by a caller that supplies a fallback.
Encore
- Number statistics reportA seeded sample run through min, max, mean, and spread.