Python newbie asks questions about recursion
ringa_lee
ringa_lee 2017-06-12 09:21:02
0
1
664

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.

ringa_lee
ringa_lee

ringa_lee

reply all(1)
Ty80

The print after return in the second piece of code cannot be executed. The function has returned.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!