Python基础-函数

来源:互联网 发布:双十一淘宝的交易额 编辑:程序博客网 时间:2024/05/22 17:00

函数

内置函数

  • 绝对值函数abs()
>>> abs(-2)2>>> abs(10)10
  • 比较函数
    需要说明的是python3 版本中已经没有cmp()函数(python2还支持),已经被 operator 模块代替了,在交互模式下使用,需要导入模块.
>>> import operator #引入 operator 模块>>> operator.eq(1,1) #判断1==1True>>> operator.lt(1,2) #判断1<2True>>> operator.le(1,2) #判断1<=2True>>> operator.ne(1,2) #判断1!=2True>>> operator.ge(1,2) #判断1>=2False>>> operator.gt(1,2) #判断1>2False
  • 数据类型转换函数
#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, worldhello, 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+yprint add(1,2)#3
0 0
原创粉丝点击