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
2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.