python 中创建函数及传递参数

 

001、创建函数

>>> def test_fun():                      ## 创建函数
...     print("hello world!")
...
>>> test_fun()                           ## 调用函数
hello world!

 

002、顺序参数、关键字参数

>>> def test_fun(x,y):                   ## 定义函数, 两个形参
...     z = x - y
...     return z
...
>>> test_fun(10, 3)                      ## 顺序参数,即x = 10, y = 3
7
>>> test_fun(x = 3, y = 10)              ## 关键字参数, 定义x = 3, y = 10
-7

 

003、默认参数

>>> def test_fun(x, y = 10):             ## 此处定义了默认参数y = 10
...     z = x + y
...     return z
...
>>> test_fun(x = 5)                      ## 当不指定y的值时, y默认为10
15
>>> test_fun(x = 5, y = 20)              ## 当指定y的值时, 默认参数不再起作用
25

 

004、收集参数

 

>>> def test_fun(*args):                         ## *+参数名
...     print("%s args!" % len(args))
...     print("second: %s" % args[1])
...
>>> test_fun(500, 600, 300, 800)
4 args!
second: 600

 

005、函数文档

>>> def test_fun(x,y):                          ## 定义函数文档
...     """
...     ssssss
...     yyyyyy
...     """
...     z = x + y
...     return z
...
>>> test_fun(x = 10, y = 40)
50
>>> print(test_fun.__doc__)                    ## 输出函数文档

        ssssss
        yyyyyy

 

>>> help(test_fun)

Help on function test_fun in module __main__:

test_fun(x, y)
ssssss
yyyyyy
(END)

 

posted @ 2022-08-06 15:05  小鲨鱼2018  阅读(189)  评论(0编辑  收藏  举报