递归代码是否超出了此函数的返回值?

时间:2017-03-05 13:31:14

标签: python recursion

我对这个python代码感到困惑:

def Counting(x):
    if x <= 0:
        return x
    else:
        print(x)
        x = x-1
        Counting(x)
    print("count up",x)
print(Counting(10))

The out put is:
10
9
8
7
6
5
4
3
2
1
count up 0
count up 1
count up 2
count up 3
count up 4
count up 5
count up 6
count up 7
count up 8
count up 9
None

我不明白为什么返回值为None?我不应该得到x的值吗?是否可以获得我选择的返回值?

谢谢

2 个答案:

答案 0 :(得分:0)

在函数中,你没有返回任何东西。

按如下方式更新功能

<强>代码

def Counting(x):
    result = None
    if x <= 0:
        return x
    else:
        print(x)
        x = x-1
        result = Counting(x)
    print("count up",x)
    return result


print Counting(10)

答案 1 :(得分:0)

  

我不明白为什么返回值为None?我不应该   得到x的值?是否有可能获得我的回报值   选择?

如果方法没有显式返回,则python返回None。这是标准的。

在第7行Counting(x)中,您没有捕获/返回返回的内容。所以当x为0且x&lt; = 0:返回0时,你忽略它。

你去print("count up", x)打印0。

现在该方法返回None,它转到递归调用者。最后回到原始方法调用None。我希望现在很清楚。

如果您将代码更改为。

def Counting(x):
    if x <= 0:
        return x
    else:
        print(x)
        x = x-1
        Counting(x)
    print("count up",x)
    return x

print(Counting(10)) # This will return 9

# here Counting(10) calls Counting(9) but ignores what it returns
# and Counting(9) calls Counting(8) but ignores what it returns
# Counting(10) finally returns x which is 9

另一方面,如果你想保留最后一个值,那么应该返回。

def Counting(x):
    if x <= 0:
        return x
    else:
        print(x)
        x = x-1
        return Counting(x)
    print("count up", x) # this line is dead code.

Counting(10) # This will return 0

# here Counting(10) returns what Counting(9) returns. 
# and Counting(9) returns what Counting(8) returns and so on....
# finally returning Counting(0)
  

是否可以获得我选择的返回值?

是的,根据您希望从递归状态返回的值,您可以获得所需的值。这是编程。您可以在逻辑上解释的任何事情都可以通过编程来完成:)