函数
一、定义函数
def my_abs(x): if x < 0: return -x else: return x
二、调用函数
my_abs(-10) # 10
三、参数
1、默认参数(默认参数必须指向不变对象)
def my_abs(x=2): if x < 0: return -x else: return x
2、可变参数(0个或任意个)
def calc(*numbers): sum = 0 for n in numbers: sum += n*n return sum print(calc(1,2,3,4)) # 30 l = [1,2,3,4] #Python允许在list或tuple前面加一个*号,把list或tuple的元素变成可变参数传进 print(calc(*l)) # 30
3、关键词参数(0个或任意个包含参数名的参数,这些参数在函数内自动组成dict),功能:扩展函数功能
def person(name, age, **kw): print('name:', name, 'age:', age, 'other:', kw) person('char', 28) # name: char age: 28 other: {} person('char', 28, city='beijing') # name: char age: 28 other: {'city': 'beijing'} person('char', 28, gender = 'M', job = 'Engineer') # name: char age: 28 other: {'gender': 'M', 'job': 'Engineer'} extra = {'city': 'beijing', 'job': 'Engineer'} person('char', 28, **extra) # name: char age: 28 other: {'city': 'beijing', 'job': 'Engineer'}
4、命名关键词参数(如果要限制关键字参数的名字,就可以用命名关键字参数,例如,只接收city
和job
作为关键字参数)
def person(name, age, *, city, job): print('name:', name, 'age:', age, city, job) person('char', 28, city='beijing', job='Engineer') # name: char age: 28 beijing Engineer