print and println@printftry-catch for Exception HandlingfinallyAs your programs become more involved, you'll often find yourself writing the same or very similar blocks of code in multiple places. This repetition can make your code longer, harder to read, and more prone to errors. If you need to change that piece of logic, you'd have to find and update every instance. Functions offer a clean solution by allowing you to package a sequence of operations into a single, named unit. You define this unit once and can then execute, or "call," it as many times as you need, potentially with different inputs each time. This approach is fundamental to writing well-structured, maintainable, and efficient Julia code.
In Julia, you define a function using the function keyword, followed by the function's name, a list of parameters enclosed in parentheses, and then the body of the function. The definition is concluded with the end keyword.
Here's the general structure:
function function_name(parameter1, parameter2, ...)
# Code block: statements that the function executes
# ...
return result # Optional: sends a value back to the caller
end
Let's break this down:
function: This keyword signals the beginning of a function definition.function_name: This is the name you give to your function. You'll use this name to call the function later. Good function names are typically descriptive and follow Julia's convention of being lowercase, with words separated by underscores if needed (e.g., calculate_area).parameters (e.g., parameter1, parameter2): These are placeholders for the values (inputs) that the function expects to receive when it's called. Parameters behave like local variables within the function. If a function doesn't need any inputs, you still use empty parentheses: function_name().function and end. This is where you write the instructions that the function will perform when executed.return result: The return keyword is used to specify the value that the function should output. When a return statement is executed, the function immediately stops and sends the result back to the part of the program that called it. If a function doesn't have an explicit return statement, it automatically returns the value of the last expression evaluated in its body. For beginners, it's often clearer to use an explicit return.end: This keyword marks the termination of the function definition.Let's start with a very simple function that doesn't take any inputs and doesn't explicitly return a value. Its purpose is just to print a greeting.
function say_hello()
println("Hello from a Julia function!")
end
In this example:
say_hello is the function's name.() are empty.println statement.return statement. When called, it will execute println and then implicitly return a special value nothing.Now, let's define a function that takes inputs (parameters) and returns a calculated value.
function add_two_numbers(x, y)
sum_value = x + y
return sum_value
end
Here:
add_two_numbers is the function name.x and y. When we call this function, we'll need to provide two values that will be assigned to x and y respectively.sum_value = x + y calculates the sum of the two parameters and stores it in a local variable sum_value.return sum_value sends the calculated sum back to the caller.Defining a function doesn't execute it. It just tells Julia what the function does. To run the code inside a function, you must "call" it. You call a function by writing its name followed by parentheses. If the function expects arguments (values for its parameters), you provide them inside the parentheses.
Let's call the functions we just defined:
# Calling the say_hello function
say_hello()
When Julia encounters say_hello(), it executes the println("Hello from a Julia function!") statement inside the say_hello function. The output will be:
Hello from a Julia function!
Now, let's call add_two_numbers. Since it expects two arguments, we need to provide them. The value returned by the function can be stored in a variable or used directly.
# Calling add_two_numbers with arguments 5 and 10
first_sum = add_two_numbers(5, 10)
println("The first sum is: ", first_sum)
# Calling it again with different arguments
second_sum = add_two_numbers(3.14, 2.71)
println("The second sum is: ", second_sum)
Output:
The first sum is: 15
The second sum is: 5.85
Notice how add_two_numbers(5, 10) passes 5 to the parameter x and 10 to the parameter y within the function. The function calculates 5 + 10, returns 15, which is then stored in the first_sum variable. The reusability aspect is clear: we called the same function add_two_numbers with different inputs to get different results without rewriting the addition logic.
The following diagram illustrates the flow of execution when first_sum = add_two_numbers(5, 10) is called:
Flow of control and data during a function call. The program passes arguments to the function, the function executes and returns a value, and then the program continues from where it left off.
It's important to distinguish between parameters and arguments:
x and y in add_two_numbers(x, y)). They are like placeholders.5 and 10 in add_two_numbers(5, 10)).For very simple functions that can be expressed in a single line of code, Julia provides a more compact syntax. This is often used for mathematical operations or straightforward transformations.
The syntax is:
function_name(parameter1, parameter2, ...) = expression
For example, our add_two_numbers function could be written concisely as:
add_two_numbers_short(x, y) = x + y
And a function to square a number:
square(n) = n * n
You call these short-form functions exactly the same way as those defined with the function...end block:
another_sum = add_two_numbers_short(7, 8)
println("Sum from short function: ", another_sum) # Output: Sum from short function: 15
squared_value = square(9)
println("9 squared is: ", squared_value) # Output: 9 squared is: 81
This compact form is merely "syntactic sugar" for the standard function...end definition when the function body is just one expression that provides the return value. It can make your code more readable for simple operations.
By defining and calling functions, you start to build more structured and manageable programs. You encapsulate logic into reusable pieces, making your code easier to understand, test, and modify. As we proceed, you'll learn more about function arguments, return values, and other features that make functions a powerful tool in Julia.
Was this section helpful?
© 2026 ApX Machine LearningEngineered with