函数
封装功能,提高应用的模块性和代码重用率
1. 定义函数
1.1 函数内的第一条语句是字符串时,该字符串就是文档字符串(docstring)
- def my_fun():
- '''我是文档字符串
- 函数内第一句是字符串时
- 该字符串就是文档字符串
- '''
- pass
- print(my_fun.__doc__)
- ''' 运行结果:
- 我是文档字符串
- 函数内第一句是字符串时
- 该字符串就是文档字符串
- '''
复制代码1.2 创建一个可以判断一个整数是否是素数的函数
- # 判断某个整数是否是素数,是返回Ture,不是返回False
- def isPrimer(num):
- if num == 1:
- return False
- for i in range(2, num//2 + 1):
- if num%i == 0:
- return False
- return True
- # 判断某个区间内的素数
- def CircleIsPrimer(head, stop):
- MyDict = {True: '素数', False: '非素数'}
- for i in range(head, stop+1):
- print(i, ' is ', MyDict[isPrimer(i)])
- # 主函数
- def main():
- print(isPrimer(2))
- CircleIsPrimer(1, 15)
- # 调用主函数
- main()
- ''' 运行结果
- True
- 1 is 非素数
- 2 is 素数
- 3 is 素数
- 4 is 非素数
- 5 is 素数
- 6 is 非素数
- 7 is 素数
- 8 is 非素数
- 9 is 非素数
- 10 is 非素数
- 11 is 素数
- 12 is 非素数
- 13 is 素数
- 14 is 非素数
- 15 is 非素数
- '''
复制代码1.3 创建一个可以输出限定数值内的斐波拉契数列函数
- def fib(num):
- a, b = 0, 1
- result = []
- while a < num:
- result.append(a)
- a, b =b, a + b
- return result
- print(fib(10))
- ''' 运行结果
- [0, 1, 1, 2, 3, 5, 8]
- '''
复制代码 2. 参数传递
在Python中,对象有不同类型的区分,变量没有类型
2.1 默认参数。定义函数时,需要从右往左给参数默认值,调用函数时,如果没有传递参数,则会使用默认参数
- def loves(who,how='sincerely love',what='Python',why='Only because I love it'):
- print(who, end=' ')
- print(how, end=' ')
- print(what)
- print(why)
- return
- loves('I')
- ''' 运行结果
- I sincerely love Python
- Only because I love it
- '''
复制代码2.2 关键字。使用关键字参数允许函数调用时参数的顺序与声明时不一致
- # 判断某个整数是否是素数,是返回Ture,不是返回False
- def isPrimer(num):
- if num == 1:
- return False
- for i in range(2, num//2 + 1):
- if num%i == 0:
- return False
- return True
- # 判断某个区间内的素数
- def CircleIsPrimer(head, stop):
- MyDict = {True: '素数', False: '非素数'}
- for i in range(head, stop+1):
- print(i, ' is ', MyDict[isPrimer(i)])
- CircleIsPrimer(stop = 15, head = 1)
- ''' 运行结果
- 1 is 非素数
- 2 is 素数
- 3 is 素数
- 4 is 非素数
- 5 is 素数
- 6 is 非素数
- 7 is 素数
- 8 is 非素数
- 9 is 非素数
- 10 is 非素数
- 11 is 素数
- 12 is 非素数
- 13 is 素数
- 14 is 非素数
- 15 is 非素数
- '''
复制代码2.3 不定长参数。加了*的参数会以元组的形式导入,存放所有未命名的变量参数。加了**的参数会以字典的形式导入
- # 2.3.1 以元组形式导入,包含形参列表之外的位置参数
- def isLovePython(who, how, what, *why):
- print(who, end=' ')
- print(how, end=' ')
- print(what)
- print(why)
- return
- isLovePython('I', 'love', 'Python', 'only', 'because', 'I', 'love', 'it')
- ''' 运行结果
- I love Python
- ('only', 'because', 'I', 'love', 'it')
- '''
复制代码- # 2.3.2 以字典形式导入,包含已定义形参对应之外的所有关键字参数
- def isLovePython(**lovePython):
- print(lovePython)
- return
- isLovePython(who='I', how='sincerely love', what='Python')
- ''' 运行结果
- {'who': 'I', 'how': 'sincerely love', 'what': 'Python'}
- '''
复制代码- # 2.3.3 二者组合使用,*形参 必须在 **形参之前
- def LovePython(who_, *how_, **info):
- print(who_)
- print(how_)
- print(info)
- return
- LovePython('I', 'need', 'Python', who='live', how='is short')
- ''' 运行结果
- I
- ('need', 'Python')
- {'who': 'live', 'how': 'is short'}
- '''
复制代码2.4 强制位置参数。限制参数的传递方式
- def my_fun(a, b, /, c, d, *, e, f):
- pass
- # a,b 必须是位置形参
- # c,d 位置形参或关键字形参
- # e,f 必须是关键字形参
复制代码 3. 解包实参列表
3.1 用*把实参从列表或元组中解包出来
- love = ['I', 'need', 'Python']
- def Printf(who: str, how: str, what: str = 'MySQL') -> None:
- print(who, '', how, '', what)
- return
- Printf(*love)
- ''' 运行结果
- I need Python
- '''
复制代码3.2 用**把实参从字典中解包出来
- love = {'who': 'I', 'how': 'need', 'what': 'Python'}
- def Printf(who: str, how: str, what: str = 'MySQL') -> None:
- print(who, '', how, '', what)
- return
- Printf(**love)
- ''' 运行结果
- I need Python
- '''
复制代码 4. Lambda 表达式
常规定义函数的语法糖,只能是单个表达式
- # 4.1 把匿名函数作为传递的实参
- # 案例1:把 python、pytorch、pandas 筛选出来
- love = ['python', 'PHP', 'pytorch', 'MySQL', 'pandas']
- loveAI = filter(lambda x: x[0] == 'p', love)
- print(list(loveAI))
- ''' 运行结果
- ['python', 'pytorch', 'pandas']
- '''
- # 案例2:字母全变大写
- love = ['python', 'PHP', 'pytorch', 'MySQL', 'pandas']
- love = map(lambda x: x.upper(), love)
- print(list(love))
- ''' 运行结果
- ['PYTHON', 'PHP', 'PYTORCH', 'MYSQL', 'PANDAS']
- '''
复制代码- # 4.2 把匿名函数作为函数返回值
- love = ['python', 'PHP', 'pytorch', 'MySQL', 'pandas']
- def LoveAI():
- return lambda x: x[0] == 'p'
- love_AI = LoveAI()
- loveAI = filter(love_AI, love)
- print(list(loveAI))
- ''' 运行结果
- ['python', 'pytorch', 'pandas']
- '''
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |