Default Parameter Values
In the previous exercise, you saw that a call with a missing argument ends with an error. But often there's a value that fits most of the time, and we only want to pass a different one now and then. Most people order a medium coffee, for example. For such cases, a parameter can have a default value: after the name of the parameter, write = and the value:
def order_coffee(drink, size="medium"):
print(f"{drink}, size: {size}")
order_coffee("Latte", "large")
order_coffee("Espresso")This prints:
Latte, size: large
Espresso, size: mediumWhen the call passes an argument for size, the function uses it. When it doesn't, the function uses the default value "medium". Without the default value, the second call would end with the error TypeError: order_coffee() missing 1 required positional argument: 'size'.
Notice that there are no spaces around the = of a default value: size="medium", unlike when you create a variable: size = "medium". It would work with spaces too; it's just how Python programmers write it.
Because arguments go into parameters in order, parameters with default values go at the end. Then you can leave out the last arguments, and the ones you pass still go into the right parameters. Python won't even let you put a parameter without a default value after one with a default value: def order_coffee(size="medium", drink): ends with the error SyntaxError: parameter without a default follows parameter with a default.
Instructions
- 1
Our shop shows most prices in euros, so the last call passes only the price. Run the program: it prints two prices and then ends with an error. Give the parameter
currencythe default value"EUR". The last line then saysPrice: 25 EUR, and the other two calls still print their own currencies. - 2
Below the function
print_price, create a functiongreetwith a parameternamewhose default value is"visitor". The function prints a greeting such asHello, Anna!. - 3
At the end of the program, call
greetonce without an argument, and once with your name as the argument. The program printsHello, visitor!and then the greeting with your name.