Python 中级:面向开发者
Jasmin Ludolf
Curriculum Manager
def average(values): """Find the mean in a sequence of values and round to two decimal places.""" average_value = sum(values) / len(values) rounded_average = round(average_value, 2) return rounded_average# 使用六个参数 print(average(15, 29, 4, 13, 11, 8))
TypeError: average() takes 1 positional argument but 6 were given
文档字符串有助于说明如何使用自定义函数
可变参数允许函数接受任意数量的参数
# 允许任意数量的位置(非关键字)参数
def average(*args):
# 函数代码保持不变
约定命名:*args
兼容多种用法,且结果可预期!
# 使用六个位置参数调用 average
print(average(15, 29, 4, 13, 11, 8))
13.33
*:将参数转换为单个可迭代对象(元组)# 跨多列表计算
print(average(*[15, 29], *[4, 13], *[11, 8]))
13.33
# 使用可变关键字参数 def average(**kwargs):average_value = sum(kwargs.values()) / len(kwargs.values()) rounded_average = round(average_value, 2) return rounded_average
可变关键字参数:**kwargs
keyword=value
# 使用六个关键字参数调用 average
print(average(a=15, b=29, c=4, d=13, e=11, f=8))
13.33
# 使用一个关键字参数(字典)调用 average
print(average(**{"a":15, "b":29, "c":4, "d":13, "e":11, "f":8}))
13.33
# 使用三个关键字参数组调用 average
print(average(**{"a":15, "b":29}, **{"c":4, "d":13}, **{"e":11, "f":8}))
13.33
Python 中级:面向开发者