后面的函数学习之后咱们发现,函数不被调用是不会间接执行的。咱们在之前的函数调用之后发现运行的后果都是函数体内print()打印进去的后果,然而有时候为了不便函数参加二次运算,咱们让函数体内不输入任何后果,而是把函数自身就当做一种后果,输入这种后果的形式就能够了解为返回函数的后果,python用return关键词来返回。上面咱们比照几种不同的函数调用后果。
一、函数的输入形式比照
1.间接应用print打印函数运行后果:间接调用函数名传参即可。
def func1(a, b): res = a + b print(res)func1(4, 9)返回后果:13
2.打印没有返回值,没有输入代码块的函数,须要把函数当做一个变量来用print输入。
def func2(a, b): res = a + bprint(func2(4, 9))返回后果:None
3.打印有返回值(return)的函数,同上,也是把函数当做一个变量来输入。
def func3(a, b): res = a + b return res # print(a) # return前面的代码不会被执行print(func3(4, 9))返回后果:13
比照下面三种模式的函数,如果咱们想用函数的后果来做运算的话,第一种状况就无奈实现,比方
func1(4, 9) * 3返回后果:TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
第二种状况自身就是None,所以疏忽,第三种状况咱们再试试
print(func3(4, 9) * 3)返回后果:39
从下面的后果能够看出,有返回值的函数用起来很不便,间接能够当做变量来应用。
二、return的作用
同时return还有完结函数代码块的性能,return之后的下一行语句不会被执行。
留神:有返回值的函数个别间接调用函数名是不执行任何后果的,赋值给变量后才会返回后果。如果一个函数没有return语句,其实它有一个隐含的语句,返回值是None,类型也是'None Type'。print是打印在控制台,而return则是将前面的局部作为返回值。”
上面再来看看return的一些特别之处。
1.能够return多个后果
def func3(a, b): res1 = a + b res2 = a - breturn res1, res2print(func3(4, 9))返回后果:13 -5
2.一个函数能够有多个return,然而只会执行第一个
def func3(a, b): res1 = a + b res2 = a - b return res1return res2print(func3(4, 9))返回后果:13
3.没有return的函数返回NoneType
def func3(a, b): res1 = a + bres2 = a - bprint(type(func2(4, 9)))返回后果:<class 'NoneType'>
三、帮忙函数
这里属于一个补充知识点,咱们在函数应用的时候不晓得传参和函数的其余用法的时候能够应用help()函数来输入开发文档中的文本提醒。
help(print)import os #文件目录操作模块os.mkdir('123')help(os.mkdir)
返回后果:
Help on built-in function print in module builtins:print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.Help on built-in function mkdir in module nt:mkdir(path, mode=511, *, dir_fd=None) Create a directory. If dir_fd is not None, it should be a file descriptor open to a directory, and path should be relative; path will then be relative to that directory. dir_fd may not be implemented on your platform. If it is unavailable, using it will raise a NotImplementedError. The mode argument is ignored on Windows.
以上是对于Python函数返回值类型和帮忙函数的解说,老手看不懂得话能够去Python自学网看对应的视频解说,会更加具体。
文章起源:www.wakey.com.cn/document-func-return.html