5.3 Function Parameters
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.
python
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:
text
2022/12/16
2022/12/01
2022/01/01
1970/01/01Default parameters must come after ordinary parameters.
Loading concept check...
Variable arguments
Use variable arguments when the number of parameters is not fixed.
*args packs positional arguments into a tuple.
python
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:
text
6
96**kwargs packs keyword arguments into a dictionary.
python
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:
text
[Alice]
Python: 85
Math: 80
Average: 82.50Loading interactive lab...
Loading concept check...
Loading practice...