0
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)

I want the print statement to be printed only once. I don't want to use if y>4 print() that defect the purpose.

I want the output to be like this:

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

3 Answers 3

3

Put the message in the else: block so it's only printed when we don't recurse.

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)
Sign up to request clarification or add additional context in comments.

4 Comments

This is exactly what I was looking for. But I don't understand how if prints the else statement and then goes back to the if to print the rest of the statements.
It prints it when the next recursion happens. After it returns, it continues with the previous invocation, just like all the other ones do.
Execute the code by hand on paper and you'll be enlightened.
Ok. Thank you for the tip
3

when you reach the stop condition print the required text:

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")

Comments

0
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)

prints

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

because it only prints at the end of recursion, where y == 1. If you do recursion where 1 isn't the end, all you need to do to create a similar effect is to locate where the final recursion is and then put a print statement in that will only activate if you're in the final recursion.

4 Comments

I'm sorry but this is not the way to do it.
@NithinGowda why? Does it not work for you? It worked for me.
I does work, look at barmar's answer. You'll know what I was looking for
@NithinGowda the code is just saying "if it's at it's final recursion, print 'all the recursive calls are done, now printing the stack'". That seems like it makes sense to me. I feel it's unfair to dismiss my answer just because it's a teeeeeeensy bit different from some other person's answer, when it works just fine and provides a solution from a different angle.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.