返回语句的目的是什么? [英] What is the purpose of the return statement?

查看:91
本文介绍了返回语句的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是return语句的简单基本解释,如何在Python中使用?

它和print语句有什么区别?

解决方案

print() 函数在控制台中写入,即打印"一个字符串.return 语句使您的函数退出并将一个值返回给它的调用者.一般来说,函数的要点是接受输入并返回一些东西.return 语句在函数准备好向其调用者返回值时使用.

例如,这是一个同时使用 print()return 的函数:

def foo():打印(来自 foo 内部的你好")返回 1

现在您可以运行调用 foo 的代码,如下所示:

如果 __name__ == '__main__':打印(要打电话给foo")x = foo()打印(称为 foo")print("foo 返回" + str(x))

如果您将其作为脚本(例如 .py 文件)而不是在 Python 解释器中运行,您将获得以下输出:

要调用 foo来自 foo 的你好叫 foofoo 返回 1

我希望这能让你更清楚.解释器将返回值写入控制台,以便我了解为什么有人会感到困惑.

这是解释器的另一个例子,它证明了这一点:

<预><代码>>>>定义 foo():... 打印(来自 foo 中的你好")...返回 1...>>>富()来自 foo 的你好1>>>定义栏():...返回 10 * foo()...>>>酒吧()来自 foo 的你好10

您可以看到,当从 bar() 调用 foo() 时,1 没有写入控制台.相反,它用于计算从 bar() 返回的值.

print() 是一个导致副作用的函数(它在控制台中写入一个字符串),但执行会从下一条语句恢复.return 导致函数停止执行并将一个值返回给调用它的任何对象.

What is the simple basic explanation of what the return statement is, how to use it in Python?

And what is the difference between it and the print statement?

解决方案

The print() function writes, i.e., "prints", a string in the console. The return statement causes your function to exit and hand back a value to its caller. The point of functions in general is to take in inputs and return something. The return statement is used when a function is ready to return a value to its caller.

For example, here's a function utilizing both print() and return:

def foo():
    print("hello from inside of foo")
    return 1

Now you can run code that calls foo, like so:

if __name__ == '__main__':
    print("going to call foo")
    x = foo()
    print("called foo")
    print("foo returned " + str(x))

If you run this as a script (e.g. a .py file) as opposed to in the Python interpreter, you will get the following output:

going to call foo
hello from inside foo
called foo   
foo returned 1

I hope this makes it clearer. The interpreter writes return values to the console so I can see why somebody could be confused.

Here's another example from the interpreter that demonstrates that:

>>> def foo():
...     print("hello from within foo")
...     return 1
...
>>> foo()
hello from within foo
1
>>> def bar():
...   return 10 * foo()
...
>>> bar()
hello from within foo
10

You can see that when foo() is called from bar(), 1 isn't written to the console. Instead it is used to calculate the value returned from bar().

print() is a function that causes a side effect (it writes a string in the console), but execution resumes with the next statement. return causes the function to stop executing and hand a value back to whatever called it.

这篇关于返回语句的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆