Python基础-函数
2016-11-07 17:15
281 查看
函数
内置函数
绝对值函数abs()>>> abs(-2) 2 >>> abs(10) 10
比较函数
需要说明的是python3 版本中已经没有cmp()函数(python2还支持),已经被 operator 模块代替了,在交互模式下使用,需要导入模块.
>>> import operator #引入 operator 模块 >>> operator.eq(1,1) #判断1==1 True >>> operator.lt(1,2) #判断1<2 True >>> operator.le(1,2) #判断1<=2 True >>> operator.ne(1,2) #判断1!=2 True >>> operator.ge(1,2) #判断1>=2 False >>> operator.gt(1,2) #判断1>2 False
数据类型转换函数
#int()函数可以把其他数据类型转换为整数 >>> int('123') 123 >>> int(11.2) 11 #str()函数把其他类型转换成 str: >>> str(123) '123' >>> str(2.33) '2.33'
当然,还有许多其它的内置函数,这里就不一一列举了.
自定义函数
python 中函数声明形式如下:def 函数名称([参数1,参数2,参数3,...]): 执行语句 比如: >>> def printName(name): ... print(name) ... >>> printName('lionel') lionel
定义默认参数
python中自带的 int()函数,其实是有两个参数的,我们既可以传入一个参数,又可以传入两个参数>>> int('12') 12 >>> int('12',8) 10 >>> int('12',16) 18
可见,如果不传入第二参数,默认就是十进制.
>>> def hello(name='world'): ... print('hello, '+name) ... >>> hello() #无参数时,会自动打印出hello, world hello, world >>> hello('messi')#有参数时,把名字打印出来 hello, messi
定义可变参数
在函数的参数前面加上’*’ 可以实现这个需求.示例如下:>>> def f(*args): ... print(args) ... >>> f('jf') ('jf',) >>> f('jf','messi') ('jf', 'messi') >>> f('jf','messi','henry') ('jf', 'messi', 'henry')
lambda函数
lambda函数又叫匿名函数,也就是说,函数没有具体的名称.lambda 函数语法:
lambda[arg1,arg2,arg3...]:expression
无参数
lambda:'hello' #lambda函数 相当于 def print(): return 'hello'
有参数
add=lambda x,y:x+y print add(1,2) #3
相关文章推荐
- Python入门笔记(18):Python函数(1):基础部分
- Python基础入门之函数二
- Python3基础 函数 收集参数+普通参数 的示例
- Python 零基础 快速入门 趣味教程 (咪博士 海龟绘图 turtle) 4. 函数
- python基础之函数的学习
- Python基础-函数-递归函数
- python基础之函数详解
- Python 基础-函数
- python基础(五) 函数参数
- python-基础笔记3-函数的参数类型
- Python学习入门基础教程(learning Python)--2.1 Python下自定义函数 .
- Python基础07 函数
- python常用函数总结 分类: python基础学习 2014-02-07 14:12 260人阅读 评论(0) 收藏
- Python基础之函数
- 【Python】读书笔记,基础函数
- Python学习入门基础教程(learning Python)--2.3.2Python函数实参详解
- python-函数基础
- Python基础(六)——重用代码:函数、模块、方法