Python函数用def指定函数名,可以指定输入参数,可以指定参数的默认值,也可以用return指定返回值。

调用时除了默认的位置赋值,也可按关键字赋值。

一、函数不带参数、没有返回值

defhello():print("hello world")

二、函数带参数、没有返回值

defhello(name):print("hello,", name)

三、函数指定返回值

1、一般情况返回值

defhello(name):return "hello," + name

2、返回True或False

Python中用内置函数bool传递任何对象来确定是True或False。

1)如果计算为0、值None、一个空串或一个空的内置数据结构,则为False

>>>bool(0)

False>>> bool(0.0)

False>>>bool(None)

False>>> bool('')

False>>> bool(' ')

True>>>bool(0)

False>>> bool(0.0)

False>>>bool(None)

False>>> bool('')

False>>>bool([])

False

2)任何非空的数据结构都计算为True

>>> bool(1)

True>>> bool(-1)

True>>> bool(0.01)

True>>> bool(' ')

True>>> bool([1,2])

True>>> bool({'a',1})

True

四、函数的说明文档

1、使用三重引号字符串写函数的说明文档

defhello():"""函数例子

输出hello world"""

print("hello world")

函数第二行的三重引号字符串,称为一个docstring(文档字符串),主要是作为一个文档,用来描述一个函数的用途,可以跨多行。

在Python Shell中输入“hello(”时会自动显示说明文档

python库怎么查看全部函数名_python库怎么查看全部函数名

也可以用help请求函数文档,结果如下:

>>>help(hello)

Help on function helloin module __main__:

hello()

函数例子

输出hello world

2、使用注解改进文档

Python 3支持一种称为注解的记法,描述函数返回类型以及所有参数类型

def hello(name:list) ->str:"""输出姓名列表"""

return ",".join(name)

代码中:list说明参数是一个列表,-> str说明返回值是字符串。

python库怎么查看全部函数名_赋值_02

五、指定参数的默认值

为某个参数默认值后,调用函数时,此参数可提供,也可不提供。

def fun1(p1:float, p2:int=1):return p1 * p2

上面函数的调用例子

>>> fun1(50)50

>>> fun1(50,2)100

>>>

六、关键字赋值

函数默认情况下是按位置赋值的,也可以按参数名来引用参数,称为关键字赋值。

以上面函数fun1为例,调用如下

>>> fun1(p1=50)50

>>> fun1(p2=2,p1=50)100

>>>

七、一个函数的参数可以为另一个函数

下面test函数接收一个函数对象func作为参数,test函数的返回结果是func的执行结果

def test(func: object, value: object) ->object:returnfunc(value)print(test(id, 123))print(test(id, test))print(test(type, test))

运行结果:

8791433376208

40410648

八、从函数返回一个函数

defouter():definner():print('这是内部函数')print('这是外部函数')returninner

i=outer()print(type(i))

i()

运行结果:type(i)的返回结果说明i是一个函数。

这是外部函数这是内部函数

九、处理任意数量和类型的函数参数

(1)使用*接收一个任意(0或多个)的参数列表

def test(*args):for a inargs:print(a, end=' ')ifargs:print()

test()#不提供参数时,不做什么

test(1) #输出:1

test(1,2,'a') #输出: 1 2 a

list= [1,2,3,'a','bc']

test(list)#输出:[1, 2, 3, 'a', 'bc']

test(*list) #加“*”会展开参数列表,输出:1 2 3 a bc

(2)使用**接收任意多个关键字参数

def test2(**kwargs):for k,v inkwargs.items():print(k, v, sep='->', end=' ')ifkwargs:print()

test2()#不提供参数时,不做什么

test2(a=10,b='abc') #输出:a->10 b->abc

dict= {'id':1,'name':'张三'}

test2(**dict) #也可使用**,输出:id->1 name->张三

(3)同时使用*args,**kwargs

def test(*args, **kwargs):ifargs:for a inargs:print(a, end=' ')print()ifkwargs:for k,v inkwargs.items():print(k, v, sep='->', end=' ')print()

test()#不提供参数时,不做什么

test(1) #输出:1

test(a=10,b='abc') #输出:a->10 b->abc

test(1,a=10,b='abc') #输出:1 a->10 b->abc