如何在递归调用中只打印一次语句? Python

How to print the statement only once which is inside recursion call? Python

def recur(y):
    if y>0:
        print(y)
        recur(y-1)
        print("all the recursive calls are done, now printing the stack")   # I want this statement printed only once
        print(y)
recur(5)

我希望打印语句只打印一次。我不想使用 if y>4 print() 这有违目的。

我希望输出是这样的:

5
4
3
2
1
all the recursive calls are done, now printing the stack
1 
2
3
4
5

将消息放在 else: 块中,以便仅在我们不递归时打印它。

def recur(y):
    if y>0:
        print(y)
        recur(y-1)
        print(y)
    else:
        print("all the recursive calls are done, now printing the stack")

recur(5)

当您达到停止条件时打印所需的文本:

def recur(y):
    if y>0:
        print(y)
        recur(y-1)      
        print(y)
    else:
        print("all the recursive calls are done, now printing the stack")
def recur(y):
    if y > 0:
        print(y)
        recur(y - 1)
        if y == 1:
            print("all the recursive calls are done, now printing the stack")   # I want this statement printed only once
        print(y)


recur(5)

打印

5
4
3
2
1
all the recursive calls are done, now printing the stack
1
2
3
4
5

因为它只在递归结束时打印,其中 y == 1。如果你在 1 不是结束的地方进行递归,你需要做的就是找到最终递归的位置来创建类似的效果是,然后在其中放置一个打印语句,只有在您处于最终递归时才会激活。