functions 3: Default Argument
Please read the blog functions 2: Passing Arguments before continuing.
Okay in printline1()
function you saw that you can change the length of the line with an argument, but you were left with calling the function with the argument always been set to vary the length of the line. Let’s say what if you want to have a function where you can pass an argument, else the function assumes something by default. Welcome to default argument. Look at the program below:
function printline2(length = 50)
println('*' ^ length)
end
printline2(10)
printline2()
Output:
**********
**************************************************
Here in the above example, function named printline2()
is coded as follows: function printline2(length = 50)
, note the length = 50
. So you can call printline2
like this printline2(10)
, where it will print a line of 10 characters long, or you can call it like printline2()
where it will print a line of 50 characters long which is the default provided.
The Jupyter notebook for this blog is available here https://gitlab.com/data-science-with-julia/code/-/blob/master/functions.ipynb.