0

I have just started learning python and written a procedure to calculate factorial of a number. I am getting a logical error. The value returned by fact function is None and the value of factorial after execution is 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
Bonifacio2
  • 3,405
  • 6
  • 34
  • 54
Saumya
  • 83
  • 11
  • You should return the recursive call's return value, `return fact(num - 1)`. You might also want to look at [this answer](http://stackoverflow.com/a/30214677/1903116) – thefourtheye Sep 16 '15 at 18:42
  • 2
    possible duplicate of [Recursive function does not return specified value](http://stackoverflow.com/questions/27691547/recursive-function-does-not-return-specified-value) – Barmar Sep 16 '15 at 18:51

1 Answers1

2

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.

Bonifacio2
  • 3,405
  • 6
  • 34
  • 54