为什么打印和返回代码块的顺序会影响返回



我正在尝试以不同的序列进行打印和返回功能。为什么代码中的顺序更改输出?

这是我的第一篇文章,所以如果它的措辞不好,我深表歉意。

我的第一个代码在(3(中所示的较长块中包含:

def function_that_prints():
     print ("I printed")
    return ("I printed")
def function_that_returns():
    return ("I returned")
f1 = function_that_prints()
f2 = function_that_returns()
print (f1)
print (f2)

结果:

I printed
I printed
I returned

,但是当您扭转它们时会改变。见下文。

def function_that_prints():
    return ("I printed")
    print ("I printed")
def function_that_returns():
    return ("I returned")
f1 = function_that_prints()
f2 = function_that_returns()
print (f1)
print (f2)

结果:

I printed
I returned

预期结果:

I printed
I printed
I returned

为什么?

在函数中到达 return时,您将退出函数,return调用后的所有内容将永远不会执行。

您可以在函数函数函数_that_print中的第二个示例中看到,返回行的行是在打印的行之前。在Python和大多数其他语言中,该函数返回时将结束。因此,很简单,返回后的行从未执行。如果要在函数内部打印函数_that_print,则必须像第一个示例一样返回之前发生。

抱歉缺乏格式。回到笔记本电脑时,我可以改善这个答案。

示例1

def function_that_prints():
     print ("I printed") # Line 1
    return ("I printed") # Line 2
def function_that_returns():
    return ("I returned") # Line 3
f1 = function_that_prints() # Will print line 1 and store returned value in f1 and doesn't print line 2 string
f2 = function_that_returns() # Doesn't print, but stores return string in f2
# Prints both the returned values
print (f1) 
print (f2)

示例2

def function_that_prints():
    return ("I printed") # Line 1
    print ("I printed") # Line 2
def function_that_returns():
    return ("I returned") # Line 3
f1 = function_that_prints() # Line 2 is never excecuted as function returns in line 1 and the returned string is stored in f1
f2 = function_that_returns() # Will just return the string from line 3 and store in f2
# Prints the returned strings
print (f1)
print (f2)

当您将函数告知 return 某物时,您基本上是在问出来该功能,除非您有如果> else 语句。现在,当您说返回后的函数内返回时,您的 print 被封装在功能中,但它不是将执行的指令的一部分。