当前位置:  首页>> 技术小册>> Python合辑10-函数

  1. def 函数名(参数1,参数2,...):
  2. """
  3. 文档注释
  4. """
  5. 代码块1
  6. 代码块2
  7. 代码块2
  8. return 返回值
  9. # def:定义函数的关键字
  10. # 函数名:是用来调用函数的
  11. # 函数名的命名必须能反映出函数的功能
  12. # 文档注释:描述该函数,来增强函数的可读性
  13. # 代码块:函数的功能实现代码
  14. # return:函数的返回值

有了函数之后,如需实现以下打印功能,我们可以使用函数来完成。

  1. # print('========================')
  2. # print('hello Albert')
  3. # print('========================')

1 先定义

  1. def print_sym(sym, count): # print_sym=<function print_msg at 0x000001B2A33698C8>
  2. print(sym * count)
  3. def print_msg(msg):
  4. print('\033[045m%s\033[0m' % msg)

2 再调用(函数名加括号就是在调用函数)

  1. print(print_sym) # 函数名对应一个内存地址
  2. print_sym('#', 30)
  3. print_msg('hello Albert')
  4. print_sym('#', 30)

关于函数的参数,现在只需要知道定义的时候有几个参数,调用的时候就传入几个参数。