0

(it returns none)---> why?

fact = 1
def factorial(n):
    if (n-1)!=0:
        global fact
        fact=fact*n
        n=n-1
        print(fact)
        factorial(n)
    else:
        return fact
      
n=int(input())
g=factorial(n)
print(g)
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • Please read https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/ and edit your question to format it suitably, tag it with the language you're using, and provide information about what you've done to diagnose the problem. – Jon Skeet Mar 01 '22 at 15:38
  • Also: https://stackoverflow.com/editing-help – 001 Mar 01 '22 at 15:40
  • Does this answer your question? [Recursive function returning none in Python](https://stackoverflow.com/questions/19215141/recursive-function-returning-none-in-python) – 001 Mar 01 '22 at 15:42
  • 2
    Because in the `if` block, you are _calling_ factorial() but not _returning_ its result. – John Gordon Aug 13 '22 at 00:07

1 Answers1

0

Because you need to return factorial(n) in factorial function, otherwise it just gets called and does not return any result in the calling function. Also, you don't need the global variable, simply pass it along with n in the factorial function itself when doing recursive call.

Also, there's a cleanest solution without any unnecessary variables:

def factorial(n):
    if n < 2:
        return 1
    else:
        return n * factorial(n-1)

And if you dont wanna reinvent the wheel just use math module:

import math

math.factorial(1234)
Daniel
  • 202
  • 1
  • 3