Parameters make functions flexible. The same function can receive different input and produce different output.
Default parameters
Parameters can have default values. If the caller does not provide a value, Python uses the default.
def format_date(year=1970, month=1, day=1):
return "%04d/%02d/%02d" % (year, month, day)
def main():
print(format_date(2022, 12, 16))
print(format_date(2022, 12))
print(format_date(2022))
print(format_date())
if __name__ == "__main__":
main()Output:
2022/12/16
2022/12/01
2022/01/01
1970/01/01Default parameters must come after ordinary parameters.
KNOWLEDGE QUIZ
QUESTION
What is the purpose of a default parameter?
Variable arguments
Use variable arguments when the number of parameters is not fixed.
*args packs positional arguments into a tuple.
def multiply(*args):
product = 1
for arg in args:
product *= arg
return product
print(multiply(1, 2, 3))
print(multiply(4, 2, 6, 1, 2))Output:
6
96**kwargs packs keyword arguments into a dictionary.
def get_score_info(name, **kwargs):
info = "[%s]\n" % name
for subject, score in kwargs.items():
info += "%s: %d\n" % (subject, score)
info += "Average: %.2f" % (sum(kwargs.values()) / len(kwargs))
return info
print(get_score_info("Alice", Python=85, Math=80))Output:
[Alice]
Python: 85
Math: 80
Average: 82.50INTERACTIVE LAB
Argument routing station
ACCESSPRO
PRO EXCLUSIVEGo further with Pro
Unlock Pro accessUnlock the complete interactive lab, deeper explanations, and curated reference answers.
KNOWLEDGE QUIZ
QUESTION
What does *args pack positional arguments into?
KNOWLEDGE QUIZ
QUESTION
What type is **kwargs inside the function?
HANDS-ON PRACTICE
Print a flat list as a 2D grid
Write print_2d_list(lst, row, col).
- Check len(lst) == row * col.
- Use nested loops.
- Print each row.
HANDS-ON PRACTICE
Build a flexible receipt function
Use a normal parameter, *items, and **options in one function.
- Define receipt(customer, *items, **options).
- Print every item.
- Use tax and currency from options with safe defaults.