【100+ python基础入门-43】Python函数return的作用和帮助函数

导读:本篇文章讲解 【100+ python基础入门-43】Python函数return的作用和帮助函数,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

前面的函数学习之后我们发现,函数不被调用是不会直接执行的。我们在之前的函数调用之后发现运行的结果都是函数体内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 + b
print(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 - b
    return res1, res2print(func3(4, 9))

返回结果:13  -5

2.一个函数可以有多个return,但是只会执行第一个

def func3(a, b):
    res1 = a + b
    res2 = a - b
    return res1
    return res2print(func3(4, 9))

返回结果:13

3.没有return的函数返回NoneType

def func3(a, b):
    res1 = a + b
    res2 = 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自学网看对应的视频讲解,会更加详细。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/73430.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!