Introduction
Function basics
More advanced concepts
Summary

Instruction

Nice!

You can also define a function that will have both mandatory and optional arguments, but mandatory arguments must come first:

def calculate_price(weight, price_per_pound=1.5, tax=0.15):
  return weight * price_per_pound * (1+tax)

You have a couple of options when you invoke the function:

  • calculate_price(170, 12.0, 0.83) – provide all arguments,
  • calculate_price(170) – provide only the mandatory argument; price_per_pound will equal 1.5, and tax will equal 0.15 in this case.
  • calculate_price(170, 12.0) – provide the mandatory argument (weight), and the first optional argument (price_per_pound); tax will have the default value of 0.15.

One question you may ask is this: when we invoke calculate_price(170, 12.0), how does Python know whether 12.0 refers to price_per_pound or tax? The answer is simple: it assigns values for optional arguments from left to right, so price_per_pound will always be chosen in this case.

Exercise

Create a function named calculate_area that will calculate the area of a circle according to the formula below:

area = pi * r * r

Where pi is a constant value, and r is the radius.

Your function should take two arguments: r (mandatory) and pi (optional, with a default value of 3.14).

Stuck? Here's a hint!

Remember to begin the argument list with the mandatory argument.