Home  >  Q&A  >  body text

Python newbie asks questions about recursion

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_leeringa_lee2686 days ago671

reply all(1)I'll reply

  • PHP中文网

    PHP中文网2017-06-12 09:23:02

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

    reply
    0
  • Cancelreply