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