return 语句的目的是什么?它与印刷有什么不同?

发布于 2024-11-30 15:59:22 字数 1173 浏览 2 评论 0原文

return 语句有什么作用?在Python中应该如何使用呢?

returnprint 有何不同?


另请参见

人们通常会尝试在函数内部的循环中使用 print 来查看多个值,并希望能够使用外部的结果。它们需要被返回,但是 return 第一次会退出该函数。请参阅如何使用“return”从循环中获取多个值?我可以将它们放入列表中吗?

通常,初学者会编写一个最终打印内容而不是返回的函数它,然后还尝试打印结果,导致意外的None。请参阅为什么在我的函数输出后打印“None”?

偶尔在 3.x 中,人们尝试将 print 的结果分配给一个名称,或者在另一个表达式中使用它,例如 input(print('prompt:')) 。在 3.x 中,print 是一个函数,因此这不是语法错误,但它返回 None 而不是显示的内容。请参阅为什么打印函数返回 None?

有时,人们会编写尝试的代码打印递归调用的结果,而不是正确返回它。就像仅仅调用该函数一样,这无法通过递归将值传播回来。请参阅为什么我的递归函数返回 None?

考虑 如何从函数获取结果(输出)?我稍后如何使用结果?对于仅关于如何使用return的问题,而不考虑打印

What does the return statement do? How should it be used in Python?

How does return differ from print?


See also

Often, people try to use print in a loop inside a function in order to see multiple values, and want to be able to use the results from outside. They need to be returned, but return exits the function the first time. See How can I use `return` to get back multiple values from a loop? Can I put them in a list?.

Often, beginners will write a function that ultimately prints something rather than returning it, and then also try to print the result, resulting in an unexpected None. See Why is "None" printed after my function's output?.

Occasionally in 3.x, people try to assign the result of print to a name, or use it in another expression, like input(print('prompt:')). In 3.x, print is a function, so this is not a syntax error, but it returns None rather than what was displayed. See Why does the print function return None?.

Occasionally, people write code that tries to print the result from a recursive call, rather than returning it properly. Just as if the function were merely called, this does not work to propagate the value back through the recursion. See Why does my recursive function return None?.

Consider How do I get a result (output) from a function? How can I use the result later? for questions that are simply about how to use return, without considering print.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

誰認得朕 2024-12-07 15:59:22

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

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

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

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

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

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

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

我希望这能让它更清楚。解释器将返回值写入控制台,这样我就可以明白为什么有人会感到困惑。

下面是解释器的另一个示例,它演示了这一点:

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

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

print() 是一个会产生副作用的函数(它在控制台中写入一个字符串),但会继续执行下一条语句。 return 导致函数停止执行并将一个值传回给调用它的函数。

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 within foo")
...     return 1
...
>>> foo()
hello within foo
1
>>> def bar():
...   return 10 * foo()
...
>>> bar()
hello 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.

慕烟庭风 2024-12-07 15:59:22

将 print 语句视为导致副作用,它使您的函数向用户写入一些文本,但它不能被其他函数使用函数。

我将尝试通过一些示例以及维基百科中的几个定义来更好地解释这一点。

这是维基百科中函数的定义

在数学中,函数将一个量(函数的参数,也称为输入)与另一个量(函数的值,也称为输出)相关联。 .

想一想。当你说函数有值时是什么意思?

这意味着您实际上可以用正常值替换函数的值! (假设这两个值是相同类型的值)

您为什么要问?

其他可以接受相同类型值作为输入的函数又如何呢?

def square(n):
    return n * n

def add_one(n):
    return n + 1

print square(12)

# square(12) is the same as writing 144

print add_one(square(12))
print add_one(144)
#These both have the same output

对于仅依赖于输入来产生输出的函数,有一个奇特的数学术语:引用透明度。再次,来自维基百科的定义。

引用透明性和引用不透明性是计算机程序各部分的属性。如果一个表达式可以被其值替换而不改变程序的行为,则称该表达式是引用透明的。

如果您刚接触编程,可能有点难以理解这意味着什么,但我认为经过一些实验你就会得到它。
但一般来说,您可以在函数中执行诸如 print 之类的操作,并且还可以在末尾添加 return 语句。

请记住,当您使用 return 时,您基本上是在说“调用此函数与写入返回的值相同”,

如果您拒绝输入自己的返回值,Python 实际上会为您插入一个返回值,这称为“无” ",这是一种特殊类型,没有任何意义,或者为 null。

Think of the print statement as causing a side-effect, it makes your function write some text out to the user, but it can't be used by another function.

I'll attempt to explain this better with some examples, and a couple definitions from Wikipedia.

Here is the definition of a function from Wikipedia

A function, in mathematics, associates one quantity, the argument of the function, also known as the input, with another quantity, the value of the function, also known as the output..

Think about that for a second. What does it mean when you say the function has a value?

What it means is that you can actually substitute the value of a function with a normal value! (Assuming the two values are the same type of value)

Why would you want that you ask?

What about other functions that may accept the same type of value as an input?

def square(n):
    return n * n

def add_one(n):
    return n + 1

print square(12)

# square(12) is the same as writing 144

print add_one(square(12))
print add_one(144)
#These both have the same output

There is a fancy mathematical term for functions that only depend on their inputs to produce their outputs: Referential Transparency. Again, a definition from Wikipedia.

Referential transparency and referential opaqueness are properties of parts of computer programs. An expression is said to be referentially transparent if it can be replaced with its value without changing the behavior of a program

It might be a bit hard to grasp what this means if you're just new to programming, but I think you will get it after some experimentation.
In general though, you can do things like print in a function, and you can also have a return statement at the end.

Just remember that when you use return you are basically saying "A call to this function is the same as writing the value that gets returned"

Python will actually insert a return value for you if you decline to put in your own, it's called "None", and it's a special type that simply means nothing, or null.

千紇 2024-12-07 15:59:22

我认为字典是你最好的参考

Return打印

简而言之:

返回返回一些东西回复给调用者打印时的功能生成文本

I think the dictionary is your best reference here

Return and Print

In short:

return gives something back or replies to the caller of the function while print produces text

水染的天色ゝ 2024-12-07 15:59:22

在 python 中,我们以 def 开始定义函数,并且通常(但不一定)以 return 结束函数。

假设我们需要一个将 2 添加到输入值 x 的函数。在数学中,我们可能会写出类似 f(x) = x + 2 的内容来描述这种关系:在 x 处计算的函数值等于 >x + 2

在 Python 中,它看起来像这样: 也就是说

def f(x):
    return x + 2

:我们定义ine一个名为f的函数,它将被赋予一个x值。当代码运行时,我们计算出x + 2,并返回该值。我们不是描述关系,而是列出计算结果必须采取的步骤。

定义函数后,可以使用您喜欢的任何参数调用它。它不必在调用代码中命名为 x,甚至不必是变量:

print f(2)
>>> 4

我们可以用其他方式编写该函数的代码。例如:

def f(x):
    y = x + 2
    return y

或者甚至

def f(x):
    x = x + 2
    return x

再次,我们按顺序执行步骤 - x = x + 2 更改 x 所指的内容(现在它意味着总和的结果),这就是通过 return x 得到 return 的内容(因为这是 *在 return 发生时的值)。

In python, we start defining a function with def, and generally - but not necessarily - end the function with return.

Suppose we want a function that adds 2 to the input value x. In mathematics, we might write something like f(x) = x + 2, describing that relationship: the value of the function, evaluated at x, is equal to x + 2.

In Python, it looks like this instead:

def f(x):
    return x + 2

That is: we define a function named f, which will be given an x value. When the code runs we figure out x + 2, and return that value. Instead of describing a relationship, we lay out steps that must be taken to calculate the result.

After defining the function, it can be called with whatever argument you like. It doesn't have to be named x in the calling code, and it doesn't even have to be a variable:

print f(2)
>>> 4

We could write the code for the function in some other ways. For example:

def f(x):
    y = x + 2
    return y

or even

def f(x):
    x = x + 2
    return x

Again, we are following steps in order - x = x + 2 changes what x refers to (now it means the result from the sum), and that is what gets returned by return x (because that's the value *at the time that the return happens).

近箐 2024-12-07 15:59:22

return 表示“从该函数输出该值”。

print 表示“将此值发送到(通常)stdout”

在 Python REPL 中,默认情况下函数的返回值将输出到屏幕(这与 print 不同)编码>它)。此输出发生在 REPL 上,不会在从 .py 文件运行代码时发生。它与 REPL 中任何其他表达式的输出相同。

这是打印的示例:

>>> n = "foo\nbar" #just assigning a variable. No output
>>> n #the value is output, but it is in a "raw form"
'foo\nbar'
>>> print(n) #the \n is now a newline
foo
bar
>>>

这是返回的示例:

>>> def getN():
...    return "foo\nbar"
...
>>> getN() #When this isn't assigned to something, it is just output
'foo\nbar'
>>> n = getN() # assigning a variable to the return value. No output
>>> n #the value is output, but it is in a "raw form"
'foo\nbar'
>>> print(n) #the \n is now a newline
foo
bar
>>>

return means "output this value from this function".

print means "send this value to (generally) stdout"

In the Python REPL, a function's return value will be output to the screen by default (this isn't the same as printing it). This output only happens at the REPL, not when running code from a .py file. It is the same as the output from any other expression at the REPL.

This is an example of print:

>>> n = "foo\nbar" #just assigning a variable. No output
>>> n #the value is output, but it is in a "raw form"
'foo\nbar'
>>> print(n) #the \n is now a newline
foo
bar
>>>

This is an example of return:

>>> def getN():
...    return "foo\nbar"
...
>>> getN() #When this isn't assigned to something, it is just output
'foo\nbar'
>>> n = getN() # assigning a variable to the return value. No output
>>> n #the value is output, but it is in a "raw form"
'foo\nbar'
>>> print(n) #the \n is now a newline
foo
bar
>>>
尝蛊 2024-12-07 15:59:22

此答案涵盖了上面未讨论的一些情况。
return 语句允许您在到达末尾之前终止函数的执行。这会导致执行流程立即返回到调用者。

第 4 行:

def ret(n):
    if n > 9:
         temp = "two digits"
         return temp     #Line 4        
    else:
         temp = "one digit"
         return temp     #Line 8
    print("return statement")
ret(10)

条件语句执行后,ret() 函数由于 return temp 而终止(第 4 行)。
因此 print("return statements") 不会被执行。

输出:

two digits   

出现在条件语句之后或控制流无法到达的地方的代码是死代码

返回值
在第 4 行和第 8 行中,return 语句用于在条件执行后返回临时变量的值。

要显示 printreturn 之间的区别:

def ret(n):
    if n > 9:
        print("two digits")
        return "two digits"           
    else :
        print("one digit")
        return "one digit"        
ret(25)

输出:

two digits
'two digits'

This answer goes over some of the cases that have not been discussed above.
The return statement allows you to terminate the execution of a function before you reach the end. This causes the flow of execution to immediately return to the caller.

In line number 4:

def ret(n):
    if n > 9:
         temp = "two digits"
         return temp     #Line 4        
    else:
         temp = "one digit"
         return temp     #Line 8
    print("return statement")
ret(10)

After the conditional statement gets executed the ret() function gets terminated due to return temp (line 4).
Thus the print("return statement") does not get executed.

Output:

two digits   

This code that appears after the conditional statements, or the place the flow of control cannot reach, is the dead code.

Returning Values
In lines number 4 and 8, the return statement is being used to return the value of a temporary variable after the condition has been executed.

To bring out the difference between print and return:

def ret(n):
    if n > 9:
        print("two digits")
        return "two digits"           
    else :
        print("one digit")
        return "one digit"        
ret(25)

Output:

two digits
'two digits'
最终幸福 2024-12-07 15:59:22

请注意,return 也可用于控制流。通过在函数中间放置一个或多个 return 语句,我们可以说:“停止执行该函数。我们要么得到了我们想要的结果,要么出了问题!”

例如,想象一下尝试实现 str.find(sub) 如果我们只有 str.index(sub) 可用(如果未找到子字符串,index 会引发 ValueError,而 <代码>查找返回<代码>-1)。

我们可以使用 try/ except 块:

def find(s: str, sub: str) -> int:
    try:
        return s.index(sub)
    except ValueError:
        return -1

这很好,而且可以工作,但表达能力不太好。目前尚不清楚什么会导致 str.index 引发 ValueError:此代码的读者必须了解 str.index 的工作原理为了理解find的逻辑。

我们可以创建代码文档本身,而不是添加文档字符串,说“...除非找不到 sub,在这种情况下返回 -1”,像这样:

def find(s: str, sub: str) -> int:
    if sub not in s:
        return -1
    return s.index(sub)

这样逻辑就很清晰了。

另一个好处是,一旦我们返回 s.index(sub) ,我们就不需要将其包装在 try/ except 中,因为 我们已经知道子字符串存在!

请参阅

Note that return can also be used for control flow. By putting one or more return statements in the middle of a function, we can say: "stop executing this function. We've either got what we wanted or something's gone wrong!"

For example, imagine trying to implement str.find(sub) if we only had str.index(sub) available (index raises a ValueError if the substring isn't found, whereas find returns -1).

We could use a try/except block:

def find(s: str, sub: str) -> int:
    try:
        return s.index(sub)
    except ValueError:
        return -1

This is fine, and it works, but it's not very expressive. It's not immediately clear what would cause str.index to raise a ValueError: a reader of this code must understand the workings of str.index in order to understand the logic of find.

Rather than add a doc-string, saying "...unless sub isn't found, in which case return -1", we could make the code document itself, like this:

def find(s: str, sub: str) -> int:
    if sub not in s:
        return -1
    return s.index(sub)

This makes the logic very clear.

The other nice thing about this is that once we get to return s.index(sub) we don't need to wrap it in a try/except because we already know that the substring is present!

See the Code Style section of the Python Guide for more advice on this way of using return.

波浪屿的海角声 2024-12-07 15:59:22

尽可能简单地说:

return 使值(通常是一个变量)可供调用者使用(例如,由使用 return< 的函数存储) /code> 位于内)。如果没有return,您的值或变量将无法供调用者存储/重用。

相比之下,print 会打印到屏幕上,但不会使值或变量可供调用者使用。

To put it as simply as possible:

return makes the value (a variable, often) available for use by the caller (for example, to be stored by a function that the function using return is within). Without return, your value or variable wouldn't be available for the caller to store/re-use.

print, by contrast, prints to the screen - but does not make the value or variable available for use by the caller.

假装不在乎 2024-12-07 15:59:22

“return”和“print”之间的区别还可以在以下示例中找到:

RETURN:

def bigger(a, b):
    if a > b:
        return a
    elif a <b:
        return b
    else:
        return a

上面的代码将为所有输入提供正确的结果。

打印:

def bigger(a, b):
    if a > b:
        print a
    elif a <b:
        print b
    else:
        print a

注意:这对于许多测试用例来说都会失败。

错误:

----  

FAILURE:测试用例输入:3、8。

            Expected result: 8  

FAILURE: 测试用例输入: 4, 3.

            Expected result: 4  

FAILURE: 测试用例输入: 3, 3.

            Expected result: 3  

您通过了 3 项测试中的 0 项案例

Difference between "return" and "print" can also be found in the following example:

RETURN:

def bigger(a, b):
    if a > b:
        return a
    elif a <b:
        return b
    else:
        return a

The above code will give correct results for all inputs.

PRINT:

def bigger(a, b):
    if a > b:
        print a
    elif a <b:
        print b
    else:
        print a

NOTE: This will fail for many test cases.

ERROR:

----  

FAILURE: Test case input: 3, 8.

            Expected result: 8  

FAILURE: Test case input: 4, 3.

            Expected result: 4  

FAILURE: Test case input: 3, 3.

            Expected result: 3  

You passed 0 out of 3 test cases

忆悲凉 2024-12-07 15:59:22

这是我的理解。 (希望它能帮助某人并且它是正确的)。

def count_number_of(x):
    count = 0
    for item in x:
        if item == "what_you_look_for":
        count = count + 1
    return count

所以这段简单的代码可以计算某事出现的次数。回报的安置意义重大。它告诉你的程序哪里需要这个值。因此,当您打印时,您将输出发送到屏幕。当你返回时,你告诉这个值去某个地方。在本例中,您可以看到 count = 0 与 return 缩进 - 我们希望值 (count + 1) 替换 0。
如果您在进一步缩进 return 命令时尝试遵循代码逻辑,则输出将始终为 1,因为我们永远不会告诉初始计数发生变化。
我希望我做对了。
哦,return 总是在函数内部。

Here is my understanding. (hope it will help someone and it's correct).

def count_number_of(x):
    count = 0
    for item in x:
        if item == "what_you_look_for":
        count = count + 1
    return count

So this simple piece of code counts number of occurrences of something. The placement of return is significant. It tells your program where do you need the value. So when you print, you send output to the screen. When you return you tell the value to go somewhere. In this case you can see that count = 0 is indented with return - we want the value (count + 1) to replace 0.
If you try to follow logic of the code when you indent the return command further the output will always be 1, because we would never tell the initial count to change.
I hope I got it right.
Oh, and return is always inside a function.

君勿笑 2024-12-07 15:59:22

return 应该用于递归函数/方法,或者您希望将返回值用于算法中的后续应用程序。

当您想要向用户显示有意义且所需的输出,并且不想让用户不感兴趣的中间结果弄乱屏幕时,应该使用 print ,尽管它们对调试你的代码。

以下代码展示了如何正确使用 returnprint

def fact(x):
    if x < 2:
        return 1
    return x * fact(x - 1)

print(fact(5))

此解释适用于所有编程语言,而不仅仅是 python

return should be used for recursive functions/methods or you want to use the returned value for later applications in your algorithm.

print should be used when you want to display a meaningful and desired output to the user and you don't want to clutter the screen with intermediate results that the user is not interested in, although they are helpful for debugging your code.

The following code shows how to use return and print properly:

def fact(x):
    if x < 2:
        return 1
    return x * fact(x - 1)

print(fact(5))

This explanation is true for all of the programming languages not just python.

请远离我 2024-12-07 15:59:22

return 是函数定义的一部分,而 print 将文本输出到标准输出(通常是控制台)。

函数是接受参数并返回值的过程。 return 用于后者,而前者则用 def 完成。

例子:

def timestwo(x):
    return x*2

return is part of a function definition, while print outputs text to the standard output (usually the console).

A function is a procedure accepting parameters and returning a value. return is for the latter, while the former is done with def.

Example:

def timestwo(x):
    return x*2
秋千易 2024-12-07 15:59:22

return 函数最好的一点是你可以从函数返回一个值,但你可以使用 print 做同样的事情,那么有什么区别呢?
基本上 return 不仅仅是返回,它以对象形式提供输出,以便我们可以将函数的返回值保存到任何变量,但我们不能使用 print 因为它是相同的就像C 编程 中的stdout/cout 一样。

按照下面的代码可以更好地理解

代码

def add(a, b):
    print "ADDING %d + %d" % (a, b)
    return a + b

def subtract(a, b):
    print "SUBTRACTING %d - %d" % (a, b)
    return a - b

def multiply(a, b):
    print "MULTIPLYING %d * %d" % (a, b)
    return a * b

def divide(a, b):
    print "DIVIDING %d / %d" % (a, b)
    return a / b


print "Let's do some math with just functions!"

age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)

print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)


# A puzzle for the extra credit, type it in anyway.
print "Here is a puzzle."

what = add(age, subtract(height, multiply(weight, divide(iq, 2))))

print "That becomes: ", what, "Can you do it by hand?"

我们现在正在为加、减、乘、编写我们自己的数学函数。需要注意的重要一点是最后一行我们说 return a + b (在 add 中)。其作用如下:

  1. 使用两个参数调用我们的函数:ab
  2. 我们打印出我们的函数正在做什么,在本例中是“ADDING”。
  3. 然后我们告诉 Python 做一些向后的事情:我们返回 a + b 的加法。您可能会这样说:“我添加 ab,然后返回它们。”
  4. Python 将这两个数字相加。然后,当函数结束时,运行该函数的任何行都可以将此 a + b 结果分配给变量。

Best thing about return function is you can return a value from function but you can do same with print so whats the difference ?
Basically return not about just returning it gives output in object form so that we can save that return value from function to any variable but we can't do with print because its same like stdout/cout in C Programming.

Follow below code for better understanding

CODE

def add(a, b):
    print "ADDING %d + %d" % (a, b)
    return a + b

def subtract(a, b):
    print "SUBTRACTING %d - %d" % (a, b)
    return a - b

def multiply(a, b):
    print "MULTIPLYING %d * %d" % (a, b)
    return a * b

def divide(a, b):
    print "DIVIDING %d / %d" % (a, b)
    return a / b


print "Let's do some math with just functions!"

age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)

print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)


# A puzzle for the extra credit, type it in anyway.
print "Here is a puzzle."

what = add(age, subtract(height, multiply(weight, divide(iq, 2))))

print "That becomes: ", what, "Can you do it by hand?"

We are now doing our own math functions for add, subtract, multiply, and divide. The important thing to notice is the last line where we say return a + b (in add). What this does is the following:

  1. Our function is called with two arguments: a and b.
  2. We print out what our function is doing, in this case "ADDING."
  3. Then we tell Python to do something kind of backward: we return the addition of a + b. You might say this as, "I add a and b then return them."
  4. Python adds the two numbers. Then when the function ends, any line that runs it will be able to assign this a + b result to a variable.
2024-12-07 15:59:22

简单的事实是,printreturn 彼此无关print 用于在终端中显示内容(对于命令行程序)。1 return 用于当您调用函数时返回结果,以便您可以在程序逻辑的下一步中使用它。

许多初学者在 Python 的解释器提示中尝试代码时会感到困惑2,如

>>> def example():
...     return 1
... 
>>> example()
1

值被显示;这不是意味着 return 显示内容吗? 。如果您在 .py 文件中尝试相同的代码,您可以亲眼看到运行该脚本不会导致显示 1

这个实际上不应该令人困惑,因为它的工作方式与任何其他表达式相同:

>>> 1 + 1
2

这会显示在交互式提示符处,但如果我们制作一个仅显示 1 + 1< 的脚本,则不会出现这种情况。 /code> 并尝试运行它。

再次强调:如果您需要将某些内容作为脚本的一部分显示,请打印它。如果您需要在下一步计算中使用它,请返回它。

秘密在于交互式提示导致显示结果,不是代码。这是提示为您执行的单独步骤,以便您可以一次查看代码如何工作,以进行测试。

现在,让我们看看 print 会发生什么:

>>> def example():
...     return 'test'
... 
>>> print(example())
test

无论我们是在交互式提示中还是在脚本中,都会显示结果。 print 明确用于显示值 - 正如我们所看到的,它的显示方式有所不同。交互式提示使用从 example 返回的值的 repr,而 print 使用值的 str

实际上:print 以文本形式向我们展示了值的样子(对于字符串,这仅表示字符串的内容)。交互式提示向我们显示值是什么 - 通常,通过编写类似于我们将使用的源代码来创建它的内容。3

但是等等 - print 是一个函数,对吧? (无论如何,在 3.x 中)。所以它返回了一个值,对吗?解释器提示符不是应该在单独的步骤中显示它吗?发生了什么?

还有一个技巧: print 返回 特殊值 None,解释器提示将忽略它。我们可以通过使用一些计算结果为 None 的表达式来测试这一点:

>>> None
>>> [None][0]
>>> def example():
...     pass # see footnote 4
... 
>>> example()
>>> 

在每种情况下,根本没有单独的行用于输出,甚至没有空行 - 解释器提示符只是返回到提示符。


1也可以用来写入文件,尽管这是一个不太常见的想法,但通常使用 .write 方法会更清晰。

2 这有时称为 REPL,代表“读取-评估-打印循环”。

3 这并不总是实用,甚至不可能 - 特别是当我们开始定义自己的类时。严格的规则是 repr 将依靠对象的 .__repr__ 方法来完成脏工作;同样,str 依赖于 .__str__

4 Python 中的函数 隐式返回 None如果它们没有显式返回值

The simple truth is that print and return have nothing to do with each other. print is used to display things in the terminal (for command-line programs).1 return is used to get a result back when you call a function, so that you can use it in the next step of the program's logic.

Many beginners are confused when they try out code at Python's interpreter prompt2, like

>>> def example():
...     return 1
... 
>>> example()
1

The value was displayed; doesn't this mean that return displays things? No. If you try the same code in a .py file, you can see for yourself that running the script doesn't cause the 1 to display.

This shouldn't actually be confusing, because it works the same way as any other expression:

>>> 1 + 1
2

This displays at the interactive prompt, but not if we make a script that just says 1 + 1 and try running it.

Again: if you need something to display as part of your script, print it. If you need to use it in the next step of the calculation, return it.

The secret is that the interactive prompt is causing the result to be displayed, not the code. It's a separate step that the prompt does for you, so that you can see how the code works a step at a time, for testing purposes.

Now, let's see what happens with print:

>>> def example():
...     return 'test'
... 
>>> print(example())
test

The result will display, whether we have this in an interactive prompt or in a script. print is explicitly used to display the value - and as we can see, it displays differently. The interactive prompt uses what is called the repr of the value that was returned from example, while print uses the str of the value.

In practical terms: print shows us what the value looks like, in text form (for a string, that just means the contents of the string as-is). The interactive prompt shows us what the value is - typically, by writing something that looks like the source code we would use to create it.3

But wait - print is a function, right? (In 3.x, anyway). So it returned a value, right? Isn't the interpreter prompt supposed to display that in its separate step? What happened?

There is one more trick: print returns the special value None, which the interpreter prompt will ignore. We can test this by using some expressions that evaluate to None:

>>> None
>>> [None][0]
>>> def example():
...     pass # see footnote 4
... 
>>> example()
>>> 

In each case, there is no separate line at all for output, not even a blank line - the interpreter prompt just goes back to the prompt.


1 It can also be used to write into files, although this is a less common idea and normally it will be clearer to use the .write method.

2 This is sometimes called the REPL, which stands for "read-eval-print loop".

3 This isn't always practical, or even possible - especially once we start defining our own classes. The firm rule is that repr will lean on the .__repr__ method of the object to do the dirty work; similarly, str leans on .__str__.

4 Functions in Python implicitly return None if they don't explicitly return a value.

君勿笑 2024-12-07 15:59:22

Return 语句——将根据您的函数返回一些值。

def example(n):
    if n == 5:
       return true
    else:
       return false

如果你调用上面的函数并传递数字 5 那么它将返回 true,否则它将返回 false。

打印功能——它将打印您提供给打印功能或打印功能括号中的内容。

def example(n):
    if n == 5:
       print("number is equal")
    else:
       print("number is not equal")

Return statement -- will return some values according your function.

def example(n):
    if n == 5:
       return true
    else:
       return false

if you call above function and you pass number 5 then it will return true else it will return false.

Printing function -- it will print content that you have given to the print function or with in print function bracket.

def example(n):
    if n == 5:
       print("number is equal")
    else:
       print("number is not equal")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文