Python函数return的用法和作用、以及帮助函数 |
您所在的位置:网站首页 › python返回函数的作用 › Python函数return的用法和作用、以及帮助函数 |
前面的函数学习之后我们发现,函数不被调用是不会直接执行的。我们在之前的函数调用之后发现运行的结果都是函数体内print()打印出来的结果,但是有时候为了方便函数参与二次运算,我们让函数体内不输出任何结果,而是把函数本身就当做一种结果,输出这种结果的方式就可以理解为返回函数的结果,python用return关键词来返回。下面我们对比几种不同的函数调用结果。 一、函数的输出方式对比1.直接使用print打印函数运行结果:直接调用函数名传参即可。 代码语言:python复制def func1(a, b): res = a + b print(res) func1(4, 9) 返回结果:132.打印没有返回值,没有输出代码块的函数,需要把函数当做一个变量来用print输出。 代码语言:python复制def func2(a, b): res = a + b print(func2(4, 9)) 返回结果:None3.打印有返回值(return)的函数,同上,也是把函数当做一个变量来输出。 代码语言:python复制def func3(a, b): res = a + b return res # print(a) # return后面的代码不会被执行 print(func3(4, 9)) 返回结果:13对比上面三种形式的函数,如果我们想用函数的结果来做运算的话,第一种情况就无法实现,比如 代码语言:python复制func1(4, 9) * 3 返回结果:TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'第二种情况本身就是None,所以忽略,第三种情况我们再试试 代码语言:python复制print(func3(4, 9) * 3) 返回结果:39从上面的结果可以看出,有返回值的函数用起来很方便,直接可以当做变量来使用。 二、return的作用同时return还有结束函数代码块的功能,return之后的下一行语句不会被执行。 注意:有返回值的函数一般直接调用函数名是不执行任何结果的,赋值给变量后才会返回结果。如果一个函数没有return语句,其实它有一个隐含的语句,返回值是None,类型也是'None Type'。print是打印在控制台,而return则是将后面的部分作为返回值。” 下面再来看看return的一些特别之处。 1.可以return多个结果代码语言:python复制def func3(a, b): res1 = a + b res2 = a - b return res1, res2 print(func3(4, 9)) 返回结果:13 -52.一个函数可以有多个return,但是只会执行第一个代码语言:python复制def func3(a, b): res1 = a + b res2 = a - b return res1 return res2 print(func3(4, 9)) 返回结果:133.没有return的函数返回NoneType代码语言:python复制def func3(a, b): res1 = a + b res2 = a - b print(type(func2(4, 9))) 返回结果:三、帮助函数这里属于一个补充知识点,我们在函数使用的时候不知道传参和函数的其他用法的时候可以使用help()函数来输出开发文档中的文本提示。 代码语言:python复制help(print)import os #文件目录操作模块 os.mkdir('123') help(os.mkdir)返回结果: 代码语言:python复制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自学网看对应的视频讲解,会更加详细。 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |