简体   繁体   English

我在Python 2.7.9中的代码有什么问题?

[英]What's wrong with my code in Python 2.7.9?

I have just started learning python and written a procedure to calculate factorial of a number. 我刚刚开始学习python,并编写了计算数字阶乘的过程。 I am getting a logical error. 我遇到了逻辑错误。 The value returned by fact function is None and the value of factorial after execution is 24. fact函数返回的值为None ,执行后的factorial值为24。

factorial = 1

def fact(num) :
    if num == 0 :
        return 1
    global factorial
    print factorial
    factorial *= num
    if num-1 > 1 :
        fact(num - 1)
    else :
        return factorial

print fact(4)
print factorial

Output : 输出:

1
4
12
None
24

You should change 你应该改变

if num-1 > 1 :
    fact(num - 1)
else:
    return factorial

to: 至:

if num-1 > 1 :
    return fact(num - 1)
else :
    return factorial

The problem was you were not returning anything except for the base case. 问题是除了基本情况外,您没有返回任何东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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