首页 python基础教程 Python函数返回值类型和帮助函数
pay pay
教程目录

Python函数返回值类型和帮助函数

日期: 二月 13, 2023, 7:06 a.m.
栏目: python基础教程
阅读: 973
作者: Python自学网-村长

摘要: 前面的函数学习之后我们发现,函数不被调用是不会直接执行的。我们在之前的函数调用之后发现运行的结果都是函数体内print()打印出来的结果,但是有时候为了方便函数参与二次运算,我们让函数体内不输出任何结果,

前面的函数学习之后我们发现,函数不被调用是不会直接执行的。我们在之前的函数调用之后发现运行的结果都是函数体内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自学网】原创作品,转载请注明出处!视频内容已申请版权,切勿转载!
回顶部