【Python基础】函数

打印 上一主题 下一主题

主题 971|帖子 971|积分 2913

函数

封装功能,提高应用的模块性和代码重用率
1. 定义函数

1.1 函数内的第一条语句是字符串时,该字符串就是文档字符串(docstring)
  1. def my_fun():
  2.     '''我是文档字符串
  3.     函数内第一句是字符串时
  4.     该字符串就是文档字符串
  5.     '''
  6.     pass
  7. print(my_fun.__doc__)
  8. ''' 运行结果:
  9. 我是文档字符串
  10.     函数内第一句是字符串时
  11.     该字符串就是文档字符串
  12. '''
复制代码
1.2 创建一个可以判断一个整数是否是素数的函数
  1. # 判断某个整数是否是素数,是返回Ture,不是返回False
  2. def isPrimer(num):
  3.     if num == 1:
  4.         return False
  5.     for i in range(2, num//2 + 1):
  6.         if num%i == 0:
  7.             return False
  8.     return True
  9. # 判断某个区间内的素数
  10. def CircleIsPrimer(head, stop):
  11.     MyDict = {True: '素数', False: '非素数'}
  12.     for i in range(head, stop+1):
  13.         print(i, ' is ', MyDict[isPrimer(i)])
  14. # 主函数
  15. def main():
  16.     print(isPrimer(2))
  17.     CircleIsPrimer(1, 15)
  18. # 调用主函数
  19. main()
  20. ''' 运行结果
  21. True
  22. 1  is  非素数
  23. 2  is  素数
  24. 3  is  素数
  25. 4  is  非素数
  26. 5  is  素数
  27. 6  is  非素数
  28. 7  is  素数
  29. 8  is  非素数
  30. 9  is  非素数
  31. 10  is  非素数
  32. 11  is  素数
  33. 12  is  非素数
  34. 13  is  素数
  35. 14  is  非素数
  36. 15  is  非素数
  37. '''
复制代码
1.3 创建一个可以输出限定数值内的斐波拉契数列函数
  1. def fib(num):
  2.     a, b = 0, 1
  3.     result = []
  4.     while a < num:
  5.         result.append(a)
  6.         a, b =b, a + b
  7.     return result
  8. print(fib(10))
  9. ''' 运行结果
  10. [0, 1, 1, 2, 3, 5, 8]
  11. '''
复制代码
2. 参数传递

在Python中,对象有不同类型的区分,变量没有类型
2.1 默认参数。定义函数时,需要从右往左给参数默认值,调用函数时,如果没有传递参数,则会使用默认参数
  1. def loves(who,how='sincerely love',what='Python',why='Only because I love it'):
  2.     print(who, end=' ')
  3.     print(how, end=' ')
  4.     print(what)
  5.     print(why)
  6.     return
  7. loves('I')
  8. ''' 运行结果
  9. I sincerely love Python
  10. Only because I love it
  11. '''
复制代码
2.2 关键字。使用关键字参数允许函数调用时参数的顺序与声明时不一致
  1. # 判断某个整数是否是素数,是返回Ture,不是返回False
  2. def isPrimer(num):
  3.     if num == 1:
  4.         return False
  5.     for i in range(2, num//2 + 1):
  6.         if num%i == 0:
  7.             return False
  8.     return True
  9. # 判断某个区间内的素数
  10. def CircleIsPrimer(head, stop):
  11.     MyDict = {True: '素数', False: '非素数'}
  12.     for i in range(head, stop+1):
  13.         print(i, ' is ', MyDict[isPrimer(i)])
  14. CircleIsPrimer(stop = 15, head = 1)
  15. ''' 运行结果
  16. 1  is  非素数
  17. 2  is  素数
  18. 3  is  素数
  19. 4  is  非素数
  20. 5  is  素数
  21. 6  is  非素数
  22. 7  is  素数
  23. 8  is  非素数
  24. 9  is  非素数
  25. 10  is  非素数
  26. 11  is  素数
  27. 12  is  非素数
  28. 13  is  素数
  29. 14  is  非素数
  30. 15  is  非素数
  31. '''
复制代码
2.3 不定长参数。加了*的参数会以元组的形式导入,存放所有未命名的变量参数。加了**的参数会以字典的形式导入
  1. # 2.3.1 以元组形式导入,包含形参列表之外的位置参数
  2. def isLovePython(who, how, what, *why):
  3.     print(who, end=' ')
  4.     print(how, end=' ')
  5.     print(what)
  6.     print(why)
  7.     return
  8. isLovePython('I', 'love', 'Python', 'only', 'because', 'I', 'love', 'it')
  9. ''' 运行结果
  10. I love Python
  11. ('only', 'because', 'I', 'love', 'it')
  12. '''
复制代码
  1. # 2.3.2 以字典形式导入,包含已定义形参对应之外的所有关键字参数
  2. def isLovePython(**lovePython):
  3.     print(lovePython)
  4.     return
  5. isLovePython(who='I', how='sincerely love', what='Python')
  6. ''' 运行结果
  7. {'who': 'I', 'how': 'sincerely love', 'what': 'Python'}
  8. '''
复制代码
  1. # 2.3.3 二者组合使用,*形参 必须在 **形参之前
  2. def LovePython(who_, *how_, **info):
  3.     print(who_)
  4.     print(how_)
  5.     print(info)
  6.     return
  7. LovePython('I', 'need', 'Python', who='live', how='is short')
  8. ''' 运行结果
  9. I
  10. ('need', 'Python')
  11. {'who': 'live', 'how': 'is short'}
  12. '''
复制代码
2.4 强制位置参数。限制参数的传递方式
  1. def my_fun(a, b, /, c, d, *, e, f):
  2.     pass
  3. # a,b   必须是位置形参
  4. # c,d   位置形参或关键字形参
  5. # e,f   必须是关键字形参
复制代码
3. 解包实参列表

3.1 用*把实参从列表或元组中解包出来
  1. love = ['I', 'need', 'Python']
  2. def Printf(who: str, how: str, what: str = 'MySQL') -> None:
  3.     print(who, '', how, '', what)
  4.     return
  5. Printf(*love)
  6. ''' 运行结果
  7. I  need  Python
  8. '''
复制代码
3.2 用**把实参从字典中解包出来
  1. love = {'who': 'I', 'how': 'need', 'what': 'Python'}
  2. def Printf(who: str, how: str, what: str = 'MySQL') -> None:
  3.     print(who, '', how, '', what)
  4.     return
  5. Printf(**love)
  6. ''' 运行结果
  7. I  need  Python
  8. '''
复制代码
4. Lambda 表达式

常规定义函数的语法糖,只能是单个表达式
  1. # 4.1 把匿名函数作为传递的实参
  2. # 案例1:把 python、pytorch、pandas 筛选出来
  3. love = ['python', 'PHP', 'pytorch', 'MySQL', 'pandas']
  4. loveAI = filter(lambda x: x[0] == 'p', love)
  5. print(list(loveAI))
  6. ''' 运行结果
  7. ['python', 'pytorch', 'pandas']
  8. '''
  9. # 案例2:字母全变大写
  10. love = ['python', 'PHP', 'pytorch', 'MySQL', 'pandas']
  11. love = map(lambda x: x.upper(), love)
  12. print(list(love))
  13. ''' 运行结果
  14. ['PYTHON', 'PHP', 'PYTORCH', 'MYSQL', 'PANDAS']
  15. '''
复制代码
  1. # 4.2 把匿名函数作为函数返回值
  2. love = ['python', 'PHP', 'pytorch', 'MySQL', 'pandas']
  3. def LoveAI():
  4.     return lambda x: x[0] == 'p'
  5. love_AI = LoveAI()
  6. loveAI = filter(love_AI, love)
  7. print(list(loveAI))
  8. ''' 运行结果
  9. ['python', 'pytorch', 'pandas']
  10. '''
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

勿忘初心做自己

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表