Python函数操作

栏目: Python · 发布时间: 8年前

内容简介:Python函数操作

Python函数的操作。

定义函数

Python里面的函数没有大括号,通过冒号 : 开始一个函数,通过缩进来编写函数内容,通过 return 返回值。

def my_abs(x):
    if x >= 0:
        return x
    else:
        return -x

如果没有写 return ,也会默认返回结果,默认结果是 None

在写函数指定参数的时候,一般是这样写:

def my_abs(x, y, z):
    if x >= 0:
        return x
    else:
        return -x


print(my_abs(-9, y = 1, z = 2))

默认参数值:

def multiply_by(a, b=2):
    return a * b


print(multiply_by(3, 47)) # print 141
print(multiply_by(3)) # print 6

函数的可变参数,使用 *

def varargs(*args):
    return args
 
varargs(1, 2, 3) #=> (1,2,3)

同时可以设置可变数量的关键字参数,使用 **

def keyword_args(**kwargs):
    return kwargs

keyword_args(big="foot", loch="ness")
# {"big": "foot", "loch": "ness"}

空函数

python 里面可以定义一个函数为空函数,使用 pass 声明:

def thePasss():
    pass

这样就定义了一个空函数,什么也不写,编译器不会报错,可以将代码成功运行,这样做的原因是为了当你在写一个函数的时候,还没想好要怎么写内容,就可放个 pass ,来先顶顶,不会造成错误。

pass 除了能在函数里面使用,还能在其他地方使用,比如在:

if age >= 18:
    pass

以上所述就是小编给大家介绍的《Python函数操作》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Iterative Methods for Sparse Linear Systems, Second Edition

Iterative Methods for Sparse Linear Systems, Second Edition

Yousef Saad / Society for Industrial and Applied Mathematics / 2003-04-30 / USD 102.00

Tremendous progress has been made in the scientific and engineering disciplines regarding the use of iterative methods for linear systems. The size and complexity of linear and nonlinear systems arisi......一起来看看 《Iterative Methods for Sparse Linear Systems, Second Edition》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具