LoslegenKostenlos loslegen

Keyword arguments

Keyword arguments are another type of argument that can be passed to a function. A keyword argument is similar in concept to the NamedTuple that we saw in the previous chapter - it gives us a name to assign to a value, which gives us a good understanding of what that value actually represents.

To declare a keyword argument, we use a semicolon ; in the function declaration to denote a keyword argument.

function my_func(; my_arg)
    return my_arg
end

When actually calling the function, the semicolon is not required.

my_func(; my_arg=1)

Keep in mind that while you can mix both positional and keyword arguments in the same function, keyword arguments must always come after positional arguments in a function declaration.

Diese Übung ist Teil des Kurses

Intermediate Julia

Kurs anzeigen

Anleitung zur Übung

  • Re-write the my_profit function to use keyword arguments.
  • Call my_profit but flip the order of the arguments, passing current_price=100.0 first, followed by previous_price=105.0.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

# Define my_profit with keyword arguments and a default argument
function my_profit(____previous_price::Float64, current_price::Float64, fees::Int64=2)
	return current_price - previous_price - fees
end

# Call my_profit
my_profit(____, ____)
Code bearbeiten und ausführen