Sub topic 5
Giving parameters default values
This chapter assumes you can write a function with def, pass arguments by position and by keyword, and use return. A default value lets a caller leave an argument out.
What a default value is
A default value is a value written into the parameter list with =. Python uses it when the caller does not supply that argument.
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Ada")) # Hello, Ada!
print(greet("Ada", "Welcome")) # Welcome, Ada!
print(greet("Ada", greeting="Hi")) # Hi, Ada!name is required because it has no default. greeting is optional. Passing a value for greeting, by position or by keyword, replaces the default.
Ordering rules
Parameters without defaults must come before parameters with defaults. Writing def f(a=1, b): raises a SyntaxError. Python could not decide what to do when a caller passes only one positional argument.
The power function from the previous chapters follows this rule:
def power(base, exponent=2):
return base ** exponent
print(power(5)) # 25
print(power(2, 10)) # 1024
print(power(exponent=3, base=2)) # 8With a keyword argument you can skip optional parameters and set a later one directly. This is useful when a function has several defaults and you want to change only one of them.
When the default is evaluated
Python evaluates a default expression once, when the def statement runs. It does not re-evaluate it on each call. Changing a variable afterwards has no effect on the stored default.
DEFAULT_GREETING = "Hello"
def greet(name, greeting=DEFAULT_GREETING):
return f"{greeting}, {name}!"
DEFAULT_GREETING = "Hi"
print(greet("Ada")) # Hello, Ada!The default was fixed as "Hello" when the function was defined, so reassigning the variable later changes nothing.
Choosing good defaults
A good default is the value most callers would pick anyway. Some guidelines:
- Make a parameter optional only when a sensible default exists. If every caller must think about the value, leave it required.
- Use simple immutable defaults such as numbers, strings, booleans and
None. - Use
Nonewhen "no value given" is itself meaningful, and handle it inside the function.
def describe(name, nickname=None):
if nickname is None:
return name
return f"{name} ({nickname})"
print(describe("Margaret")) # Margaret
print(describe("Margaret", "Maggie")) # Margaret (Maggie)Compare with is None, not == None or a truthiness check. A caller might pass an empty string on purpose, and if not nickname would treat that the same as a missing argument.
Common errors
| Mistake | Result | Fix |
|---|---|---|
| Required parameter after a default | `SyntaxError` | Reorder, or give it a default |
| Expecting the default to update later | Old value is used | Pass the value explicitly or use `None` |
| Using `if not value` to test for a missing argument | Valid values such as `0` are treated as missing | Test `value is None` |
Exercise
What does this code print, and why? limit = 10 def check(value, maximum=limit): return value <= maximum limit = 5 print(check(7))
Show answer
It prints True. The default for maximum was evaluated as 10 when the def statement ran. Reassigning limit to 5 afterwards does not change the stored default, so the call compares 7 <= 10.
Exercise
Write a function repeat(text, times=2) that returns text repeated times times. What do repeat("ab") and repeat("ab", times=3) return?
Show answer
def repeat(text, times=2): return text * times repeat("ab") returns "abab" and repeat("ab", times=3) returns "ababab".