First code:
# -*- coding:gb2312 -*-
# 递归阶乘
def getnum(num):
if num > 1:
print(num)
return num * getnum(num - 1)
else:
print(num)
return num
result = getnum(5)
print(result)
The first code execution result:
Second code:
# -*- coding:gb2312 -*-
# 递归阶乘
def getnum(num):
if num > 1:
return num * getnum(num - 1)
print(num)
else:
return num
print(num)a
result = getnum(5)
print(result)
The second code execution result:
My question:
I added the print(num) statement to the function. Why can the first code print out 5 4 3 2 1 and then 120? Why does the second code print out? The result is only 120, but not 5 4 3 2 1? Logically speaking, I have already written all the print statements, so I should print them.
The
print
afterreturn
in the second piece of code cannot be executed. The function has returned.