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. 【读书笔记】iOS-ARC-循环引用-解决办法

    一,循环引用最常见的代码类型. - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading ...

  2. git 错误:

    git  错误: $ git commit -afatal: Unable to create 'e:/git/Android/XXXXXX/.git/index.lock': File exists ...

  3. html中相似的标签、属性的区别

    [1]<i></i> 和 <em></em>标签 相同:都是表示斜体. 区别: (1)<em>表示被强调呈现的内容,<i>是物理 ...

  4. android Activity生命周期(设备旋转、数据恢复等)与启动模式

    1.Activity生命周期     接下来将介绍 Android Activity(四大组件之一) 的生命周期, 包含运行.暂停和停止三种状态,onCreate.onStart.onResume.o ...

  5. 5个示例带你学习AngularJS

    直到现在,你或许已经听说过AngularJS了,一个改变你对web应用思考方式,由谷歌开发的令人兴奋的开源框架.关于它的文章已经写得非常之多,但我发现还是要写些给那些更喜欢快速且实际例子的开发者.当今 ...

  6. 【JSP】JSP基础学习记录(二)—— JSP的7个动作指令

    2.JSP的7个动作指令: 动作指令与编译指令不同,编译指令是通知Servlet引擎的处理消息,而动作指令只是运行时的动作.编译指令在将JSP编译成Servlet时起作用:而处理指令通常可替换成JSP ...

  7. MySQL出现Waiting for table metadata lock的原因以及解决方法

    转自:http://ctripmysqldba.iteye.com/blog/1938150 (有修改) MySQL在进行alter table等DDL操作时,有时会出现Waiting for tab ...

  8. dotNET使用DRPC远程调用运行在Storm上的Topology

    Distributed RPC(DRPC)是Storm构建在Thrift协议上的RPC的实现,DRPC使得你可以通过多种语言远程的使用Storm集群的计算能力.DRPC并非Storm的基础特性,但它确 ...

  9. Activiti之 Exclusive Gateway

    一.Exclusive Gateway Exclusive Gateway(也称为XOR网关或更多技术基于数据的排他网关)经常用做决定流程的流转方向.当流程到达该网关的时候,所有的流出序列流到按照已定 ...

  10. iOS获取本地沙盒视频封面图片

    最近做了个小应用,有涉及到本地视频播放及列表显示. 其中一个知识点就是获取本地存储视频,用来界面中的封面显示. 记录如下: -(UIImage*) thumbnailImageForVideo:(NS ...