Skip to content
Advertisement

Confusion in recursion program of python

Hey guys can anyone explain that output to me?

Don’t get why its counting down again.

def kaboom(i):
    print("first Print: ", i)
    if i < 3:
        kaboom(i+1)
    print("second Print: ", i)

OUTPUT:

first Print:  1
first Print:  2
first Print:  3
second Print:  3
second Print:  2
second Print:  1

Advertisement

Answer

To understand this you need to understand how recursion works. It works on the concept of stacks. You can have a look at the following link, to get a clear understanding : https://www.freecodecamp.org/news/how-recursion-works-explained-with-flowcharts-and-a-video-de61f40cb7f9/

You are calling the same function again if i<3, so it’s printing first print and so on.. but after it’s returned, the execution won’t end there right. It has to execute rest of the method, which is second print.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement