Meet Python: little notes 3 - function
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的更多相关文章
- Meet python: little notes 4 - high-level characteristics
Source: http://www.liaoxuefeng.com/ ♥ Slice Obtaining elements within required range from list or tu ...
- Meet Python: little notes 2
From this blog I will turn to Markdown for original writing. Source: http://www.liaoxuefeng.com/ ♥ l ...
- Meet Python: little notes
Source: http://www.liaoxuefeng.com/ ❤ Escape character: '\' - '\n': newline; - '\t': tab; - '\\': \; ...
- python 100day notes(2)
python 100day notes(2) str str2 = 'abc123456' print(str1.endswith('!')) # True # 将字符串以指定的宽度居中并在两侧填充指 ...
- 70个注意的Python小Notes
Python读书笔记:70个注意的小Notes 作者:白宁超 2018年7月9日10:58:18 摘要:在阅读python相关书籍中,对其进行简单的笔记纪要.旨在注意一些细节问题,在今后项目中灵活运用 ...
- python之函数(function)
#今天来学习一下函数,function# 定义一个函数的时候,函数不会被执行,只有调用函数,函数才会执行## 定义函数# # 1.def是创建函数的关键字,创建函数# # 2.函数名# # 3.()# ...
- Python编程核心内容 ---- Function(函数)
Python版本:3.6.2 操作系统:Windows 作者:SmallWZQ 截至上篇随笔<Python数据结构之四——set(集合)>,Python基础知识也介绍好了.接下来准备干 ...
- [Python Study Notes]匿名函数
Python 使用 lambda 来创建匿名函数. lambda这个名称来自于LISP,而LISP则是从lambda calculus(一种符号逻辑形式)取这个名称的.在Python中,lambda作 ...
- [Python Study Notes]字符串处理技巧(持续更新)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ...
随机推荐
- Android 常见对话框
1.对话框通知(Dialog Notification) 当你的应用需要显示一个进度条或需要用户对信息进行确认时,可以使用对话框来完成. 下面代码将打开一个如图所示的对话框: public void ...
- Swift 初步了解
Swift 初步了解 前言: 本篇博客会结合OC对Swift进行简单介绍. OC 用NSLog输出日志 NSLog(@"旭宝爱吃鱼"); Swift 用print输出日志 prin ...
- UITableView传值(自己使用)(属性,代理传值)
今天有些匆忙. 效果图如下: 代码如下: #import <UIKit/UIKit.h> #import "FirstViewController.h" @interf ...
- python 判断学期与学年
9,10,11,12,1 第一学期 2,3,4,5,6,7 第二学期 其中8月份放假,暂且放入第一学期.因为大部分学校都选在8月底开学 import datetime def getXNandXQ() ...
- Struts
Struts是基于MVC的框架,它进一步的对MVC进行了封装. MVC 概念 MVC全名是Model View Controller,是模型(model)—视图(view)—控制器(controlle ...
- mac 终端 常用指令
开始正式研究ios 应用开发,由于是从C开始学起,所以学习下常用的mac终端指令,方便后续常用操作. mac 终端 常用指令: 1.ls指令 用途:列出文件 常用参数 -w 以简洁的形式列出所有文件和 ...
- yii2增加验证码详细步骤
作者:白狼 出处:http://www.manks.top/article/yii2_captcha本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留 ...
- 编译hadoop2.6.0
具体情况比较曲折:hadoop2.6.0编译不过 错误如下: 这个kms模块始终编译不过,最后得出结论国内的aliyun maven仓库有问题, 在编译hadoop2.2.0 可以通过,因为这个版本的 ...
- 0018 Java学习笔记-面向对象-类的基本要素
类与对象 大街上一个个的人,就是一个个对象 类是对一群对象的抽象,比如人都有性别.年龄.姓名,都会吃饭.睡觉等.姓名性别可以抽象为变量,吃饭睡觉可以抽象为方法,像下面一样定义个类来形容人 public ...
- js判断游览器是移动端还是PC端
js判断网页游览器是移动端还是PC端 <script type="text/javascript"> function browserRedirect() { var ...