Mojo Function Arguments and Return Values

Mojo functions have two main concepts: arguments and return values. Using this method, we can pass data into a function and get data from a function; it is essential for writing clean, reusable, and efficient Mojo programs.

What Are Function Arguments in Mojo?

Sometimes we need to give some extra information to the function, and that extra information is an argument.

Arguments are like the ingredients that you give to a function so it can make the result you want.

A parameter is like an empty box, and the argument is an actual value that we have stored in the box. For example:

fn greet(name: str):
print("Hello,", name)

greet("John") /// output: Hello, John

you can see, name is the parameter and “John” is the argument in this code.

Types of Function Arguments in Mojo

Mojo programming supports multiple ways to pass arguments. such as:

  • Positional Arguments
  • Default Arguments
  • Keyword Arguments
  • Variable Number of Arguments

1) Positional Arguments

Positional arguments mean, when we call the function, the order of values we pass matches the order of parameters.

For example: Suppose you are ordering food in a restaurant when the waiter writes it down in sequence.

Example:

fn add(a: Int, b: Int):
print("Sum:", a + b)

add(5, 10)
# Output: Sum: 15

Here:

  • a gets 5
  • b gets 10

If you swapped it:

add(10, 5)

Result is the same (15), but if you were doing subtraction:

fn subtract(a: Int, b: Int):
print("Result:", a - b)

subtract(10, 5) # Result: 5
subtract(5, 10) # Result: -5 different result

Real-life example: When entering an ATM pin, if you change the order of digits, it won’t work.

2) Default Arguments

These are the default arguments. When you give a pre-set value to a parameter, and if the user doesn’t pass a value, to function automatically uses the default. This method is useful for optional information; no need to always pass it.

fn greet_user(name: str = "Guest"):
print("Welcome,", name)

greet_user() # Output: Welcome, Guest
greet_user("Prince") # Output: Welcome, Prince

In this code, it will use the guest if no name is available. If a name is provided, it replaces the default.

3) Keyword Arguments

In these arguments, we can pass values by naming the parameters instead of relying on order. This is important for improving readability, avoiding mistakes in order, and helpful in functions with many parameters.

For example:

fn introduce(name: str, age: Int):
print(f"{name} is {age} years old.")

introduce(age=25, name="Rohan")
# Output: Rohan is 25 years old.

If we wrote “age” first, so Mojo matches names, not positions.

Real-life example: Writing an address on a package doesn’t matter in what order you write first, but labels (City, State, Zip) should be correct.

4) Variable Number of Arguments

Sometimes we don’t know how many values we will pass into a function. Mojo can collect them all for you.

a) *args → Multiple Positional Arguments (Tuple)

*args will collects all extra positional arguments into a tuple. For example:

fn total_sum(*numbers: Int):
var total = 0
for num in numbers:
total += num
print("Total:", total)

total_sum(5, 10, 15)
# Output: Total: 30

b) **kwargs → Multiple Keyword Arguments (Dictionary-like)

**kwargs collects all extra keyword arguments into a dictionary-like object.

Example:

fn display_info(**data):
for key, value in data.items():
print(f"{key}: {value}")

display_info(name="John", city="London")
# Output:
# name: John
# city: London

Real-life example: When we fill out an online form, each entry has a label (Name, City, Email) and a value.

What Are Return Values in Mojo?

A return value is the result a function sends back after doing its work.

Imagine you ordering food in a restaurant and you give your order (arguments) for what you want. Then the kitchen (the function) cooks it, and the waiter brings back your dish (return value – result).

If a function doesn’t have a return, so you get nothing in Mojo, this is none.

For example:

fn square(num: Int) -> Int:
return num * num

result = square(6)
print("Square:", result) # Square: 36

In this example:

  • num is the argument you pass in.
  • The function calculates num * num.
  • return sends that value back so you can use it later.

Multiple return values:

fn calculate(a: Int, b: Int) -> (Int, Int):
return (a + b, a * b)

sum_val, product_val = calculate(4, 5)
print("Sum:", sum_val) # Sum: 9
print("Product:", product_val) # Product: 20

Here, the function returns two results at once (a tuple).

Arguments + Return Together:

fn celsius_to_fahrenheit(celsius: Float) -> Float:
return (celsius * 9/5) + 32

temp_c = 25
temp_f = celsius_to_fahrenheit(temp_c)
print(f"{temp_c}°C is {temp_f}°F")
# 25°C is 77.0°F
  • Argument: 25 (the temperature in Celsius you give to the function).
  • Return value: 77.0 (the converted Fahrenheit value you get back).

Also Learn this Topics:

Exercise: “Smart Cafeteria Bill Calculator”

building a small program for a school cafeteria that calculates the final bill for a student.
The program should be with the following terms:

  1. Use positional arguments for item price and quantity.
  2. Use a default argument for tax rate (default = 5%).
  3. Allow keyword arguments to apply an optional discount.
  4. Support variable arguments (*args) to add extra charges (like takeaway box, cold drink, etc.).
  5. Support **kwargs to display extra customer info (like name, class, etc.).
  6. Return the final bill amount.

Code in Mojo

fn calculate_bill(price: Float, quantity: Int, tax_rate: Float = 5.0, *extra_charges: Float, discount: Float = 0.0, **customer_info) -> Float:
# Step 1: Base cost
var subtotal = price * quantity

# Step 2: Add extra charges (if any)
for charge in extra_charges:
subtotal += charge

# Step 3: Apply discount (if any)
if discount > 0:
subtotal -= subtotal * (discount / 100)

# Step 4: Apply tax
var total = subtotal + (subtotal * (tax_rate / 100))

# Step 5: Display customer info
print("Customer Info:")
for key, value in customer_info.items():
print(f"{key}: {value}")

# Step 6: Return final bill
return total


# Example Usage
final_amount = calculate_bill(
50.0, 2, # Positional arguments
5.0, # Default tax (can be changed)
10.0, 5.0, # *args (extra charges: cold drink, takeaway box)
discount=10, # Keyword argument
name="Rohan", class_name="8B" # **kwargs (extra info)
)

print(f"Final Bill: ₹{final_amount}")

Expected Output

Customer Info:
name: Rohan
class_name: 8B
Final Bill: ₹103.95

Leave a Comment