Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how variables are stored and treated in recursion function in python?

I am quite confused with the code below.

def a(x):
    print(x)    
    if x > 0:
        a(x - 1)
    print(x)    #I am confused with this print statement 

a(5)

The above code outputs:

5
4
3
2
1
0
0
1
2
3
4
5

Up till the 0 I understand how it prints, but then why it prints in ascending order.
Variable x is changing so what I thought the output would be is the last assigned value of x that is 0.
My predicted output:

5
4
3
2
1
0
0
0
0
0
0
0

So how does it track the value of x...?
Can someone explain in brief what actually happens in recursive functions and how variables are stored in it.

like image 248
hello world Avatar asked Feb 13 '17 13:02

hello world


People also ask

How are variables used in recursion?

The code works on the basic principle of recursion. Every time it does not find the element at the position it will keep incrementing the value of variable recS by 1 . If the element is not found and it reaches at the last element then it simply returns -1 .

How is recursion data stored?

A recursive function calls itself, the memory for a called function is allocated on top of memory allocated to the calling function and a different copy of local variables is created for each function call.

How does recursive function work in Python?

Recursive Functions in Python A recursive function is a function defined in terms of itself via self-referential expressions. This means that the function will continue to call itself and repeat its behavior until some condition is met to return a result.

Where the values are stored in recursion?

Memory Allocation in Recursion. When a function is called, its memory is allocated on a stack. Stacks in computing architectures are the regions of memory where data is added or removed in a last-in-first-out (LIFO) process. Each program has a reserved region of memory referred to as its stack.


1 Answers

You have to understand that for each function call the x is local. So it means that the second call to f has a different x. To visualize this: you can see it like:

f(x=5)
    print(x) # this x = 5
    f(x=4)
        print(x) # this x = 4
        f(x=3)
            print(x) # this x = 3
            f(x=2)
                print(x) # this x = 2
                f(x=1)
                    print(x) # this x = 1
                    f(x=0)
                        print(x) # this x = 0
                        print(x) # this x = 0
                    print(x) # this x = 1
                print(x) # this x = 2
            print(x) # this x = 3
        print(x) # this x = 4
    print(x) # this x = 5

So in your recursive calls, there are six xes. Each of the x variables can have a different value and changing them one level deeper has no impact on the level above, etc.

like image 149
Willem Van Onsem Avatar answered Oct 02 '22 11:10

Willem Van Onsem