简体   繁体   中英

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,

  • 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 如何阅读

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.

您必须在分步列表中构建一个调用堆栈:当b == 0 ,函数mult返回到上次调用的位置,即rest = ...行,而不是该行print ...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM