Xivilai
Xivilai

Reputation: 2521

Python basic program understanding

I am trying to understand this program but can't get my head around it. Could anyone suggest where i'm going wrong?

def mult(a, b):
    if b == 0:
        return 0
    rest = mult(a, b - 1)
    value = a + rest
    return value

print("3 * 2 = ", mult(3, 2))

In the above Python Script,

I followed your comments and put this together to make it easier to follow How to read

Upvotes: 1

Views: 265

Answers (3)

Cory Kramer
Cory Kramer

Reputation: 117856

You are using mult recursively, and it returns to rest, so you will be updating that value each time you come back from the function. A few print statements might help clear up what is going on.

def mult(a, b):
    if b == 0:
        print "b = 0"
        return 0
    rest = mult(a, b - 1)
    value = a + rest
    print "rest", rest, "value", value
    return value

mult(3,2)

Output

b = 0
rest 0 value 3
rest 3 value 6
6

Upvotes: 1

Rob Watts
Rob Watts

Reputation: 7146

The problem in your understanding lies with where the call to mult(3, 0) returns to. That call does not return to the line print..., it returns to the line rest = mult(a, b-1). So then value = a + rest will result in value having the value of 3 + 0 = 3. Then the return value line will return to rest = mult(a, b-1) again. When it hits return value again, that is when it will return to the print statement.

Upvotes: 3

Daniel
Daniel

Reputation: 42748

You have to build a call-stack in your step-by-step-list: when the b == 0 the function mult returns to the place where it was last called, that was the line rest = ... and not the line print ....

Upvotes: 1

Related Questions