1

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,

  • The line print("3 * 2 = ", mult(3, 2)) is run
  • The Mult function is called
  • In the Mult Function b == 2 so the if condition return FALSE
  • The Line rest = Mult(a, b -1) is next and calls the Mult function again on new values (3,1)
  • In the Mult Function b == 1 so the if condition return FALSE
  • The Line rest = Mult(a, b -1) is next and calls the Mult function again on new values (3,0)
  • In the Mult Function b == 0 so the if condition return TRUE
  • The value 0 is returned by the if condtion
  • The program Prints "3 * 2 = 0"?

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

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 ....

Comments

1

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

Comments

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.