Skip to main content
 首页 » 编程设计

python之这个 Python 函数不应该一直返回 6 吗

2025年05月04日10lvdongjie

我是 Python 的新手,正在学习函数。我遇到了以下功能,并且不知所措地了解它是如何工作的。在我看来,无论 b 的值如何,答案都应该始终为 6,但事实并非如此。

代码

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) 

我对发生的事情的理解

  1. 因为 b 不为 0,所以继续
  2. rest 被赋值为 3, 1 并再次运行函数
  3. 因为 b 是 1 并且等于 0,所以它继续 rest
  4. rest 被赋值为 3, 0 并再次运行函数
  5. 由于 b 现在为零,因此返回值 0
  6. 然后继续到 value,它的值为 3 + 3,因为 a 的值为 3,而 rest 的值为 3即 (3,0)
  7. 它返回值 6

但是如果我分配mult(3,4),它返回值12。根据我的理解,这是不可能的。显然,我不了解逻辑流程。我做错了什么?

请您参考如下方法:

这个函数的基本逻辑是:

让我们(添加 a 并从 b 中减去 1)直到 b == 0。像这样对您来说可能更有意义:

def mult(a, b): 
    value = 0 
    while b > 0: 
        b = b - 1 
        value = value + a 
    return value 

只是代替了 while 循环,您的函数不断调用自身。我设法联系到了 mult 本人,他愿意解释:

Hi, my name is mult and I'm a Recurser. Recursers are a common breed in Computer Sciencia and we have a special feature; we can clone ourselves. Sadly I was cursed with the inability to multiply. Still, I wanted to live my dream as a multiplier and I did manage to find a way to do it. Here's how:

When you asks me to multiply (a, b), I spawn one clone and ask him (a, b - 1). The clone repeats this process until a clone is spawned that gets asked (a, 0). When that happens (there is a line of myself + b clones then), he answers to the clone that spawned him: 0. That clone in turn adds a to what he was just told (the first time would be 0 + a) and answers this to the clone in front of him. This process repeats until I get answered by the clone I spawned myself. I add a to that and return this as a final answer to you!

def mult(a, b): 
    # Should I ask a clone? 
    if b == 0: 
        # No! I reply 0 to my asker. 
        return 0 
 
    # Yes! I spawn a clone and ask him (a, b - 1) and wait for an answer to 
    # store in 'rest' 
    rest = mult(a, b - 1) 
 
    # I take the answer and add to it the 'a' I was told 
    value = a + rest 
 
    # I return the value I calculated to my asker 
    return value 
 
print "3 * 2 = ", mult(3, 2)  # Here someone asks me (3, 2)