6. Default values
A parameter can have a default value. Write it as parameter=value in the definition. If the caller omits that argument, Python uses the default:
basehas no default, so it is required.exponent=2is optional; when omitted,exponentis2.- Parameters with defaults must come after parameters without defaults.
- An explicit argument always overrides the default.
Coming from JavaScript? Defaults are evaluated once, when the function is defined, not on every call. Never use a mutable default such as items=[]; use None and create the list inside the function.
Use a default value
Define greet(name="world") that prints Hello, world! when called with no arguments. Call greet().
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Override the default
Define greet(name="world") that prints Hello, <name>!. Call it with the argument "Ada". The explicit argument replaces the default.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
A default in a calculation
Define power(base, exponent=2) that returns base ** exponent. Print power(3). With only one argument, exponent keeps its default value 2.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Compare default and explicit arguments
Define power(base, exponent=2) as above. Print power(3), then print power(2, 5). The first call uses the default; the second overrides it.
Print exactly:
Create a free account to save your progress and unlock chapter 2.