Mojo Functions
A function is a named piece of code you can run as often as you like. You write it once, give it a name, and then call it by that name whenever you need it. You’ve already written one: main. Mojo functions use def, just like Python, but with one big difference: you have to say what type each argument is.
Defining and calling a function
Section titled “Defining and calling a function”Here’s a function that prints a greeting, and a main that calls it twice:
def say_hello(): print("Hello!") print("Nice to see you.")
def main(): say_hello() say_hello()Output:
Hello!Nice to see you.Hello!Nice to see you.The parts are:
defstarts a function definition.say_hellois the name. Function names uselower_snake_case.()holds the arguments. This function takes none, but the parentheses are still required.- The indented block after the colon is the body: the code that runs when you call it.
To call a function, write its name followed by parentheses: say_hello(). Without the parentheses, nothing gets called.
Arguments need a type
Section titled “Arguments need a type”Most functions need some input. You list the inputs (called arguments) inside the parentheses, each with a name and a type:
def greet(name: String): print("Hello,", name)
def greet_times(name: String, times: Int): for _ in range(times): print("Hi,", name)
def main(): greet("Ana") greet_times("Bo", 2)Output:
Hello, AnaHi, BoHi, Boname: String means “this function takes one value, calls it name, and it must be a String”. When you call greet("Ana"), the value "Ana" is handed to name for the duration of that call.
In Python you can leave the type out. In Mojo you can’t:
def greet(name): print("Hello,", name)
def main(): greet("Ana")hello.mojo:1:11: error: argument type must be specifieddef greet(name): ^~~~mojo: error: failed to parse the provided Mojo source moduleThe types are what let Mojo check your calls before the program runs. Pass the wrong kind of value and you find out right away:
def greet(name: String): print("Hello,", name)
def main(): greet(42)hello.mojo:5:11: error: invalid call to 'greet': value passed to 'name' cannot be converted from 'IntLiteral[42]' to 'String' greet(42) ~~~~~ ^~hello.mojo:1:5: note: function declared heredef greet(name: String): ^mojo: error: failed to parse the provided Mojo source modulePassing too many or too few arguments is caught the same way, with messages like missing required argument: 'name' or unexpected argument.
Returning a value
Section titled “Returning a value”A function can also hand a value back to whoever called it. You write the type of that value after an arrow, ->, and send it back with return:
def square(x: Int) -> Int: return x * x
def area(width: Float64, height: Float64) -> Float64: return width * height
def main(): var s = square(7) print(s) print(area(3.0, 4.5)) print(square(2) + square(3))Output:
4913.513-> Int says “this function gives back an Int”. The call square(7) turns into that value, so you can store it in a variable, print it, or use it in a bigger expression like square(2) + square(3).
return also ends the function right away. Any code after it in the same block doesn’t run.
The return type is checked too. If you promise an Int, you have to give back an Int:
def double(x: Int) -> Int: return "two"
def main(): print(double(2))hello.mojo:2:12: error: cannot implicitly convert 'StringLiteral["two"]' value to 'Int' return "two" ^~~~~mojo: error: failed to parse the provided Mojo source moduleThe Mojo manual’s page on functions covers the full anatomy of a function, including the parts we’ll get to later.
Functions that don’t return anything
Section titled “Functions that don’t return anything”When a function doesn’t give anything back, leave out the arrow. Writing -> None means the same thing. You can still use a bare return to stop early:
def print_if_positive(x: Int) -> None: if x <= 0: return print(x, "is positive")
def main(): print_if_positive(5) print_if_positive(-2) print_if_positive(10)Output:
5 is positive10 is positiveFor -2, the function hits return and stops before the print.
Every path has to return
Section titled “Every path has to return”If a function promises a value, every way through it must end in a return. Here, a negative number would fall off the end of the function with nothing to return:
def sign(x: Int) -> String: if x > 0: return "positive"
def main(): print(sign(2))hello.mojo:1:5: error: return expected at end of function with resultsdef sign(x: Int) -> String: ^mojo: error: failed to run the pass managerPython would quietly return None here. Mojo refuses to build it. The fix is to cover the other cases:
def sign(x: Int) -> String: if x > 0: return "positive" elif x < 0: return "negative" return "zero"
def main(): print(sign(2), sign(-7), sign(0))Output:
positive negative zeroArguments are read-only
Section titled “Arguments are read-only”Inside a function, you can read an argument, but you can’t change it. This surprises people coming from Python:
def add_one(x: Int): x += 1
def main(): var n = 5 add_one(n) print(n)hello.mojo:2:5: error: expression must be mutable for in-place operator destination x += 1 ^mojo: error: failed to parse the provided Mojo source moduleBy default, a function gets a read-only view of the value you pass in. That’s safe, because the function can’t change your variables behind your back, and it’s cheap, because a big value like a long list doesn’t have to be copied. When you really do want a function to change the caller’s variable, put mut in front of the argument:
def add_one(mut x: Int): x += 1
def main(): var n = 5 add_one(n) add_one(n) print(n)Output:
7With mut, the function works on the caller’s n itself, so the change sticks. There are a few more of these keywords (var, out, ref), and they get a full lesson in Mojo Argument Conventions. For now, read-only by default and mut to change it is all you need.
Functions can call functions
Section titled “Functions can call functions”A function body can call other functions, including ones defined further down the file. Mojo reads the whole file before running anything, so the order doesn’t matter:
def main(): print(describe(3)) print(describe(12))
def describe(n: Int) -> String: if is_big(n): return "big" return "small"
def is_big(n: Int) -> Bool: return n > 10Output:
smallbigA function can even call itself. That’s called recursion. Here’s the classic factorial (5! = 5 × 4 × 3 × 2 × 1):
def factorial(n: Int) -> Int: if n <= 1: return 1 return n * factorial(n - 1)
def main(): print(factorial(5)) print(factorial(10))Output:
1203628800The if n <= 1 line is what stops it. Without a stopping case, a recursive function calls itself forever (until the program crashes).
Don’t ignore a returned value
Section titled “Don’t ignore a returned value”If you call a function that returns something and then don’t use the result, Mojo warns you, since that’s often a mistake:
def square(x: Int) -> Int: return x * x
def main(): square(4) print("done")hello.mojo:5:11: warning: 'Int' value is unused; assign to '_' to discard the result square(4) ~~~~~~^~~ _ =It’s only a warning, so the program still runs and prints done. If you really don’t need the value, write _ = square(4) to say so, and the warning goes away.
Functions that can fail
Section titled “Functions that can fail”Some operations can fail at runtime, like turning the text "abc" into a number. In Mojo, a function that might fail has to say so with raises. A plain def isn’t allowed to call something that can fail unless it deals with the error:
def to_number(s: String) -> Int: return Int(s)
def main(): print(to_number("42"))hello.mojo:2:15: error: cannot call function that may raise in a context that cannot raise return Int(s) ~~~^~~hello.mojo:2:15: note: try surrounding the call in a 'try' block return Int(s) ^hello.mojo:1:5: note: or mark surrounding function as 'raises'def to_number(s: String) -> Int: ^mojo: error: failed to parse the provided Mojo source moduleThe notes give you both fixes. The simplest is to add raises after the arguments. Then main has to be raises too, because it calls a function that can fail:
def to_number(s: String) raises -> Int: return Int(s)
def main() raises: print(to_number("42") + 1)Output:
43Errors get their own lessons, starting with Mojo Errors. For now, just know that raises exists and why the compiler asks for it.
Docstrings
Section titled “Docstrings”You can describe what a function does with a string right below the def line, like in Python. It doesn’t change how the code runs, but editors show it when you hover over the function:
def celsius_to_fahrenheit(c: Float64) -> Float64: """Convert a temperature from Celsius to Fahrenheit.""" return c * 9.0 / 5.0 + 32.0
def main(): print(celsius_to_fahrenheit(100.0)) print(celsius_to_fahrenheit(-40.0))Output:
212.0-40.0Mojo Comments has more on docstrings.
Coming from Python?
Section titled “Coming from Python?”| Python | Mojo | |
|---|---|---|
| Define a function | def f(x): |
def f(x: Int): (type required) |
| Return type | Optional hint | -> Int (required if you return a value) |
Missing return |
Returns None |
Compile error |
| Change an argument | Rebinds a local name | Not allowed unless the argument is mut |
| A function that can fail | Any function | Must be marked raises |
The Mojo tips for Python developers list more of these differences.
Practice
Section titled “Practice”1. Rectangle helpers
Section titled “1. Rectangle helpers”Write two functions: perimeter(width: Int, height: Int) -> Int and is_square(width: Int, height: Int) -> Bool. In main, print the perimeter of a 3 by 5 rectangle, then whether a 4 by 4 rectangle is a square.
Hint: the perimeter is 2 * (width + height), and == gives you a Bool.
Show solution
def perimeter(width: Int, height: Int) -> Int: return 2 * (width + height)
def is_square(width: Int, height: Int) -> Bool: return width == height
def main(): print(perimeter(3, 5)) print(is_square(4, 4))Output:
16TrueBoth functions promise a type with -> and keep that promise with return. width == height is already a Bool, so you can return it directly.
2. Fix the function
Section titled “2. Fix the function”This program doesn’t build. Fix it so it prints Grade: B.
def grade(score): if score >= 90: return "A" elif score >= 80: return "B"
def main(): print("Grade:", grade(85))Hint: there are two problems: one in the def line and one at the end of the function.
Show solution
def grade(score: Int) -> String: if score >= 90: return "A" elif score >= 80: return "B" return "C"
def main(): print("Grade:", grade(85))Output:
Grade: Bscore needs a type, and the function needs -> String because it returns text. It also needs a return for scores below 80, or Mojo reports “return expected at end of function with results”.
3. Count down
Section titled “3. Count down”Write a recursive function countdown(n: Int) that prints n, then n - 1, and so on down to 1, then prints Liftoff!.
Hint: when n is 0, print Liftoff! and return. Otherwise print n and call countdown(n - 1).
Show solution
def countdown(n: Int): if n == 0: print("Liftoff!") return print(n) countdown(n - 1)
def main(): countdown(3)Output:
321Liftoff!The n == 0 case is the stopping point. Every other call does a little work and hands a smaller number to the next call.
- Define a function with
def name(arguments):and call it withname(...). - Every argument needs a type:
def greet(name: String). - Declare a return type with
-> Typeand give the value back withreturn. Every path must return. - Functions with no result can leave out the arrow (or write
-> None). - Arguments are read-only by default. Use
mutwhen a function should change the caller’s variable. - A function that can fail must be marked
raises. - Functions can be defined in any order and can call themselves (recursion).
Next up: function arguments, with default values, keyword arguments and functions that take any number of values.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Functions (Mojo manual): the official guide to defining functions, arguments and return values.
- Function declarations reference: the exact syntax of a
def, including effects likeraises. - Errors (Mojo manual): how raising functions and
try/exceptwork. - Mojo tips for Python developers: Python habits that change in Mojo, functions included.