您的位置:首页 > 编程语言 > Python开发

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 函数