Positional arguments recap
In the Introduction to Julia course, you covered the basics of a function and how to pass arguments into a function. Before you look at more advanced functions, let's quickly recap and introduce some new terminology.
Remember that a function takes in an input and produces an output. Functions are a way to organize your code and to re-use your code effectively. The same code placed inside a function can run faster than the same code placed outside a function, so it is important to take advantage of the benefits that writing functions can offer.
When you specify the arguments of a function, you are specifying them in a set order. These are called positional arguments. Positional arguments are simply arguments that are listed in order and, when calling the function, must be passed to the function in that same order. Julia uses the position of the arguments to determine the parameter to map each input value to.
In the below example, you will write a function my_profit
that takes in two positional arguments, previous_price
and current_price
. As these are positional arguments, it is important to get the order correct.
This exercise is part of the course
Intermediate Julia
Exercise instructions
- Define the function
my_profit
and return the difference between thecurrent_price
and theprevious_price
arguments. - Call
my_profit
using aprevious_price
of 100 and acurrent_price
of 105.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Define my_profit with two positional arguments
function ____(____, ____)
return ____ - ____
end
# Call my_profit
my_profit(____, ____)