Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python return语句的使用点_Python_Python 3.x_Function_Return - Fatal编程技术网

Python return语句的使用点

Python return语句的使用点,python,python-3.x,function,return,Python,Python 3.x,Function,Return,我很好奇使用return语句有什么意义 def give_me_five(): five = 5 return five number = give_me_five() print("Here's what I got from give_me_five():", number) 上面的代码显示了以下结果 Here's what I got from give_me_five(): 5 如您所见,当您只需在print中键入5时,我从give_me_five:,5中得到了如下

我很好奇使用return语句有什么意义

def give_me_five():
    five = 5
    return five

number = give_me_five()
print("Here's what I got from give_me_five():", number)
上面的代码显示了以下结果

Here's what I got from give_me_five(): 5
如您所见,当您只需在print中键入5时,我从give_me_five:,5中得到了如下信息:使用return语句的确切意义是什么?为什么它甚至需要创建一个函数来设置值5?

为什么需要return 尝试删除返回。然后打印出来

Here's what I got from give_me_five(): None
如果不返回5,则无法在函数之外恢复它

这就是你需要回报的原因。但是

为什么需要函数 在您的示例中,您的函数总是返回相同的值,因此不需要它,但假设您有一个更复杂的函数,该函数基于输入返回

def give_me_more(n)
    return n + 1
此函数并不总是返回相同的值,因此它更有用。但是你应该问:等等,我不能在代码中用n+1替换这个函数吗

我们不能没有功能吗? 是的,但是请记住,函数可能比上面的例子复杂得多

def get_factors(n):
    factors = []
    for i in range(int(math.sqrt(n))):
        if n % i == 0:
            factors.append(i)
            factors.append(n / i)
    return sorted(factors)

是否每次要获取数字的因子时都要在脚本中插入此代码?当然不是,为了能够重用代码,您需要编写函数。而这反过来又需要回报。

。。它返回值?不需要该函数。事实上,这些代码都不需要打印文本有什么用?。我假设这只是一个例子。假设这不是哲学上的天真凝视,您可以使用return来指定函数调用的值。如果您的函数应该合理地返回一个值,例如某物\n.strip应该返回某物,那么您必须从中返回,否则它的值将为None。举个更有说服力的例子:尝试编写询问用户名的代码,然后打印Hello!然后试着写一个函数,在返回打印之前将名称大写。这是两个完全无关的问题。第一个问题是为什么要使用return?第二个问题是为什么我需要一个函数来给我五个?如果您不知道为什么应该或不应该使用return,那么在带着问题来到stackoverflow之前,您应该先做一个基本的编程教程。