一、函数的定义
一个Python函数的定义格式如下:
def funcname(parameter_list) :
pass
1.参数列表parameter_list可以没有
2.Python函数使用return返回结果,如果没有return,则默认返回结果是None
3.pass是默认的函数体,在Python中可以通过编译
二、定义和调用函数
#2.1.自定义相加函数
def add(x, y):
result = x + y
return result
#2.2.自定义打印函数
def printResult(x):
print(x)
#调用函数方法1:参数按序传入
result1 = add(100,200)
printResult(result1) #打印:300
#调用函数方法2:参数使用关键字,可无序传入
result2 = add(y=200,x=400)
printResult(result2) #打印:600
三、让函数返回多个结果
def getTodayInfo():
year = "2018"
month = "5"
day = "20"
return year,month,day
#取值方法1:索引取值
today = getTodayInfo()
print(today[0],today[1],today[2]) #打印:2018 5 20
#取值方法2:序列解包,推荐使用
year,month,day = getTodayInfo()
print(year,month,day) #打印:2018 5 20
四、默认参数
函数的默认参数是在形参的地方设置默认值,如下面代码中的contry、province字段;默认参数必须要设置在形参列表的必须参数(如name,age)之后
def printPersonInfo(name,age,country="中国",province="北京"):
print("------打印个人信息------")
print("国籍: "+ country)
print("省份: "+ province)
print("姓名: "+ name)
print("年龄: "+ age)
#按序传值
printPersonInfo("风恣","18岁")
'''
------打印个人信息------
国籍: 中国
省份: 北京
姓名: 风恣
年龄: 18岁
'''
#无序传值,使用关键字
printPersonInfo("风中恣者","19岁",province="河南")
'''
------打印个人信息------
国籍: 中国
省份: 河南
姓名: 风中恣者
年龄: 19岁
‘''
五、可变参数*args
使用可变参数*args,可以设置函数可以传入任意多个参数,这多个参数在函数调用时自动组装为一个tuple
1.为函数设置可变参数*args,传入任意多个参数
def addTotal(*numbers):
total = 0
for num in numbers:
total = total + num
return total
#传入0个参数
total0 = addTotal()
print("total1:" + str(total0)) #打印:0
#传入1个参数
total1 = addTotal(1,5)
print("total2:" + str(total1)) #打印:6
#传入2个参数
total2 = addTotal(1,5,9)
print("total3:" + str(total2)) #打印:15
2.数组、元组等对象在可变参数函数中的使用
#如果已经有一个list或者tuple,要调用一个可变参数可以这样做:
nums = [1,2,3,4]
total4 = addTotal(*nums)
print("total4:" + str(total4)) #打印:10
六、关键字参数*kw
使用关键字参数**kw,可以设置函数传入任意多个含有参数名的参数,这多个关键字参数在函数调用时自动组装为一个dict
1.为函数设置可变参数**kw,传入任意多个参数
def printStudentInfo(name,age,**kw):
print('name:'+name + "\t" + "age:" + str(age))
print(kw)
#只传入必须参数
printStudentInfo("小明",18)
'''
#打印:
name:小明 age:18
{}
'''
#传入必须参数和国籍
printStudentInfo("小明",18,country='China')
'''
#打印:
name:小明 age:18
{'country': 'China'}
'''
#传入必须参数和国籍、省份
printStudentInfo("小明",18,country='China',province="beijing")
'''
#打印:
name:小明 age:18
{'country': 'China', 'province': 'beijing'}
'''
2.已经存在的dict对象使用关键字函数
otherInfo = {'country': 'China', 'province': 'HeNan'}
printStudentInfo("小丽", 20 ,**otherInfo)
'''
#打印:
name:小丽 age:20
{'country': 'China', 'province': 'HeNan'}
'''
3.检查关键字参数中的元素
def printStudentInfo1(name,age,**kw):
if 'country' in kw:
print("传入了country参数")
if 'province' in kw:
print("传入了province参数")
print('name:'+name + "\t" + "age:" + str(age))
print(kw)