函数

简介: 函数

内置函数


Python解释器内置了许多始终可用的功能和类型。它们在这里按字母顺序列出。


官方地址:(http://docs.python.org/3/library/functions.html)




内建功能

abs() delattr() hash() memoryview() set()
all() dict() help() min() setattr()
any() dir() hex() next() slice()
ascii() divmod() id() object() sorted()
bin() enumerate() input() oct() staticmethod()
bool() eval() int() open() str()
breakpoint() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()


部分内置函数示例


# 定义变量a, b = - 1, 2c = [1, 2, 3, 4]
d = []# abs:返回参数的绝对值print(abs(a))  # 1print(abs(b))  # 2# allprint(all(c))# bin转换为二进制print(bin(10))  # 0b1010# oct转换为八进制print(oct(b))  # 0o2# int转换为十进制print(int(0b1010))  # 10# hex转换为十六进制print(hex(b))  # 0x2# anyprint(any(d))  # False# hash:返回给定对象的哈希值。# 比较相等的两个对象也必须具有相同的哈希值,但是相反的情况不一定成立。print(hash(hex(50)))  # -8192991178175214004...


自定义函数


# 定义函数: 形参为内部变量提供占位的作用,此时当调用函数时,我们需要传入实际参数def 函数名(形参1,形参2...):
      语句


空函数


如果想定义一个什么事也不做的空函数,可以用pass语句:


def nop():
    pass


pass语句什么都不做,那有什么用?实际上pass可以用来作为占位符,比如现在还没想好怎么写函数的代码,就可以先放一个pass,让代码能运行起来。


pass还可以用在其他语句里,比如:


if age >= 18:
    pass


缺少了pass,代码运行就会有语法错误。


参数检查


调用函数时,如果参数个数不对,Python解释器会自动检查出来,并抛出TypeError


>>> my_abs(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: my_abs() takes 1 positional argument but 2 were given


但是如果参数类型不对,Python解释器就无法帮我们检查。试试my_abs和内置函数abs的差别:


>>> my_abs('A')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in my_abs
TypeError: unorderable types: str() >= int()
>>> abs('A')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'str'


当传入了不恰当的参数时,内置函数abs会检查出参数错误,而我们定义的my_abs没有参数检查,会导致if语句出错,出错信息和abs不一样。所以,这个函数定义不够完善。


调用函数


我们定义如下函数,然后执行。可结果是没有任何响应。


def func():
    print(1)


原因是我们并没有调用函数


def func():
    print(1)
func()# 此时就会输出1


返回值


# 定义函数def 函数名(形参1,形参2...):
      语句      return 结果1, 结果2,结果3


# 示例: def func(a, b):
    return a * b
print(func(2, 2))# 4


小结


定义函数时,需要确定函数名和参数个数;


如果有必要,可以先对参数的数据类型做检查;


函数体内部可以用return随时返回函数结果;


函数执行完毕也没有return语句时,自动return None


函数可以同时返回多个值,但其实就是一个tuple。

目录
相关文章
|
2月前
|
存储 编译器 C++
13函数
13函数
11 0
|
4月前
函数(二)
函数(二)
13 0
|
9月前
|
C语言
C语言知识点之 函数2
C语言知识点之 函数2
31 0
|
5月前
|
前端开发 JavaScript
Less的函数的介绍
Less的函数的介绍
25 0
|
5月前
|
算法 编译器
函数(2)
函数(2)
26 0
|
5月前
|
存储 程序员 C语言
函数(1)
函数(1)
53 0
|
算法 编译器 C语言
函数部分的详细讲解
函数部分的详细讲解
|
程序员 C语言
|
编译器 C语言 C++
C++——函数
C++——函数
C++——函数
|
Java vr&ar
函数那些题 — P1
函数那些题 — P1
函数那些题 — P1