Source: http://www.liaoxuefeng.com/

♥ Function

  • In python, name of a function could be assigned to a variable, for example:
>>> a = abs;
>>> a(-12)
12
  • function definition:
def funtion_name(input_variable):
function body
return variables # usually *return* signifies the end of the function,
# without which function will return *None*. # Define a null function
def nop()
pass # *pass* could be used as a placeholder, to ensure a smooth running
def
  • import a self-defined function:
from name_of_function_definition_file (without .py) import function_name
  • two functions:

    1 isinstance: check type of parameter;

    2 raise TypeError('...'): return TypeError with '...' as additional information.
  • multiple returned values are actually one tuple;

Parameters

  • Default parameters

    Note that defalut parameters must be unchangable objects.
# Set 'Westeros' and 'dead' as default parameters for 'loaction' and 'status' respectively
def game_of_thorn(name, gender, location = 'Westeros', status = 'dead'):
print('name: ', name)
print('gender: ', gender)
print('location: ', location)
print('status: ', status) >>> game_of_thorn('Eddard Satrk', 'M')
name: Eddard Stark
gender: M
location: Westeros
status: dead >>> game_of_thorn('Benjen Stark', 'M', 'the Wall')
name: Roose Bolton
gender: M
location: the North
status: dead # You could ignore the order of input parameters as long as you assign
# the inputs directly to certain parameters
>>> game_of_thorn('Cersei Lannister', 'F', status = 'alive')
name: Cersei Lannister
gender: F
location: Westeros
status: alive
  • Variable parameters
# An example
def calc(*numbers):
sum = 0
for n in numbers: # variable parameters are treated as a tuple
sum = sum + n * n
return sum >>> calc(1, 2)
5 >>> nums = [1, 2, 3]
>>> calc(*nums) # list or tuple inputs could be sent in as variables parameters as well
14
  • Keyword parameter

    Variable parameters are treated as a dict inside the function.
def person(name, age, **kw):   # kw as keyword parameter
print('name:', name, 'age:', age, 'other:', kw) >>> person('Michael', 30)
name: Michael age: 30 other: {} >>> person('Adam', 45, gender='M', job='Engineer')
name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'} >>> extra = {'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, **extra)
name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}
  • Named keyword parameter
def person(name, age, *, city, job):   # Only those using 'city' and 'job' as
# keys will be accepted as keyword parameters
print(name, age, city, job) >>> person('Jack', 24, city='Beijing', job='Engineer')
Jack 24 Beijing Engineer # if there is alrealy a variable parameters in the function, then '*,'
# is not needed for named keyword parameters
def person(name, age, *args, city, job):
print(name, age, args, city, job)

Note

1 for named keyword parameters, parameter name is always needed when using the function;

2 named keyword parameter could be assigned a default value;

3 all the parameters could be used in one time, while the input order should be: regular parameter, default parameter, variable parameter (*argus), named keyword parameter and keyword parameter(**kw).

# Any fuction could be called using func(*args, **kw)
def f1(a, b, c=0, *args, **kw):
print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw) def f2(a, b, c=0, *, d, **kw):
print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw) >>> args = (1, 2, 3, 4)
>>> kw = {'d': 99, 'x': '#'}
>>> f1(*args, **kw)
a = 1 b = 2 c = 3 args = (4,) kw = {'d': 99, 'x': '#'} >>> args = (1, 2, 3)
>>> kw = {'d': 88, 'x': '#'}
>>> f2(*args, **kw)
a = 1 b = 2 c = 3 d = 88 kw = {'x': '#'}

Recursive function

Recursive function is the one call itself. But a stack flow may appear with multiple recursion. One way to avoid the situation is : tail recursion.

A recursive function is tail recursive if the final result of the recursive call is the final result of the function itself (https://wiki.haskell.org/Tail_recursion). Tail recursion occupies constant RAM, thus could effectively avoid stack overflow during function calling.

Meet Python: little notes 3 - function的更多相关文章

  1. Meet python: little notes 4 - high-level characteristics

    Source: http://www.liaoxuefeng.com/ ♥ Slice Obtaining elements within required range from list or tu ...

  2. Meet Python: little notes 2

    From this blog I will turn to Markdown for original writing. Source: http://www.liaoxuefeng.com/ ♥ l ...

  3. Meet Python: little notes

    Source: http://www.liaoxuefeng.com/ ❤ Escape character: '\' - '\n': newline; - '\t': tab; - '\\': \; ...

  4. python 100day notes(2)

    python 100day notes(2) str str2 = 'abc123456' print(str1.endswith('!')) # True # 将字符串以指定的宽度居中并在两侧填充指 ...

  5. 70个注意的Python小Notes

    Python读书笔记:70个注意的小Notes 作者:白宁超 2018年7月9日10:58:18 摘要:在阅读python相关书籍中,对其进行简单的笔记纪要.旨在注意一些细节问题,在今后项目中灵活运用 ...

  6. python之函数(function)

    #今天来学习一下函数,function# 定义一个函数的时候,函数不会被执行,只有调用函数,函数才会执行## 定义函数# # 1.def是创建函数的关键字,创建函数# # 2.函数名# # 3.()# ...

  7. Python编程核心内容 ---- Function(函数)

    Python版本:3.6.2  操作系统:Windows  作者:SmallWZQ 截至上篇随笔<Python数据结构之四——set(集合)>,Python基础知识也介绍好了.接下来准备干 ...

  8. [Python Study Notes]匿名函数

    Python 使用 lambda 来创建匿名函数. lambda这个名称来自于LISP,而LISP则是从lambda calculus(一种符号逻辑形式)取这个名称的.在Python中,lambda作 ...

  9. [Python Study Notes]字符串处理技巧(持续更新)

    ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ...

随机推荐

  1. c中的指针

    一. 指针前奏 1. 指针的重要性 指针是C语言中非常重要的数据类型,如果你说C语言中除了指针,其他你都学得很好,那你干脆说没学过C语言. 2. 小需求 l void change(int  n)函数 ...

  2. iOS通讯录开发

    场景一:直接选择一个联系人的电话号码 这里不需要先获取所有的联系人自己做联系人列表,直接使用系统自带的AddressBookUI/ABPeoplePickerNavigationController. ...

  3. IOS开发之开发者账号遇到的bug

    今天使用开发者账号过期的问题,文件显示 其实今天的问题和这个没有关系,即使上面显示此证书的签发者无效,有时候也是可以用的. 我这里情况比较奇葩,刚刚生成的开发者账号,显示还是"......无 ...

  4. 转:JQuery.Ajax之错误调试帮助信息

    今天发现一篇讲Ajax比较好的文章,汇总下,作为自己的知识储备. 下面是Jquery中AJAX参数详细列表: 参数名 类型 描述 url String (默认: 当前页地址) 发送请求的地址. typ ...

  5. 1.5 基础知识——GP2.3 提供资源(Resources) 与 GP2.4 分配职责(Responisbility)

    摘要: 没有资源和落实权责,将无法做好事情,这是很多公司很多人都懂的道理.但很多做CMMI改进的公司,号称很多核心人员负责过程改进,其实是兼职挂牌而已,有些甚至招聘应届生作为过程改进的主力…… 如此这 ...

  6. pentaho cde 选择性的显示多列数据

    在业务需求中,有时候会有这种需要,就是查出来可多列数据,而我只想画出来其中的一列或者说某一列,而pentaho会默认画出查出来的所有数据,而不断的更改数据源又太麻烦,这时就要用到resders方法了. ...

  7. jquery 基础教程[温故而知新二]

    子曰:“温故而知新,可以为师矣.”孔子说:“温习旧知识从而得知新的理解与体会,凭借这一点就可以成为老师了.“ 尤其是咱们搞程序的人,不管是不是全栈工程师,都是集十八般武艺于一身.不过有时候有些知识如果 ...

  8. log4j 日志信息的引入(通用版)——解决项目运行过程中的日志信息

    定义 log4j是Apache的一个开放源代码项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台.文件.GUI组件,甚至是套接口服务器.NT的事件记录器.UNIX Syslog守护进程 ...

  9. stm32之NVIC

    非本人原创,转载自http://blog.csdn.net/denghuanhuandeng/article/details/8350392 STM32的NVIC理解 例程:  /* Configur ...

  10. 新版Microsoft Azure Web管理控制台 - Microsoft Azure New Portal - (3)

    之前我们多次提到过Resource Manager,也知道Resource Manager是Microsoft Azure提供的一种新型资源管理模式.在Service Management模式(Cla ...