关于python:Python函数中retuen的作用和用法以及帮助函数的介绍

11次阅读

共计 2197 个字符,预计需要花费 6 分钟才能阅读完成。

后面的函数学习之后咱们发现,函数不被调用是不会间接执行的。咱们在之前的函数调用之后发现运行的后果都是函数体内 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, res2
print(func3(4, 9))
返回后果:13  -5

2. 一个函数能够有多个 return,然而只会执行第一个

def func3(a, b):
    res1 = a + b
    res2 = a - b
    return res1
return res2
print(func3(4, 9))
返回后果:13

3. 没有 return 的函数返回 NoneType

def func3(a, b):
    res1 = a + b
res2 = a - b
print(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

正文完
 0