5.3 函数参数
参数(parameter)让函数变得灵活。相同函数可以接收不同输入,得到不同结果。
默认参数
参数可以有默认值。这样的参数叫默认参数(default parameter)。如果调用函数时没有传入对应参数,就使用默认值。
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()运行结果:
text
2022/12/16
2022/12/01
2022/01/01
1970/01/01默认参数必须放在普通参数后面。否则 Python 无法判断调用时传入的值应该对应哪个参数。
正在加载概念检查...
可变参数
如果参数数量不固定,可以使用可变参数(variable argument)。
*args 会把多个位置参数(positional argument)打包成一个元组。
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))运行结果:
text
6
96**kwargs 会把多个关键字参数(keyword argument)打包成一个字典。
python
def get_score_info(name, **kwargs):
info = "[%s]\n" % name
for subject, score in kwargs.items():
info += "%s: %d\n" % (subject, score)
info += "平均分:%.2f" % (sum(kwargs.values()) / len(kwargs))
return info
print(get_score_info("Alice", Python=85, Math=80))运行结果:
text
[Alice]
Python: 85
Math: 80
平均分:82.50正在加载交互实验...
正在加载概念检查...
正在加载本节练习...