1
def factorial_recursive(n):
    while n > 1:
        factorial = factorial * n
        factorial_recursive(n - 1)
    return factorial
num = input("Please enter the number whose factorial you want to find ")
num = int(num)
factorial = 1
if num == 0:
    print("The factorial of 0 is 1")
elif num < 0:
    print("The factorial of a negative number cannot be computed")
elif num == 1:
    print("The factorial of 1 is 1")
else:
    print("The factorial is", factorial_recursive(num))

Error message:

UnboundLocalError                         Traceback (most recent call last)
<ipython-input-28-c3621871e051> in <module>()
     16 else:
     17     factorial = 1
---> 18     print("The factorial is", factorial_recursive(num))

<ipython-input-28-c3621871e051> in factorial_recursive(n)
      2 def factorial_recursive(n):
      3     while n > 1:
----> 4         factorial = factorial * n
      5         factorial_recursive(n - 1)
      6     return factorial

UnboundLocalError: local variable 'factorial' referenced before assignment

I have seen the working code of using recursive functions to find the factorial of a number. I was trying to do it on my own and I have traced the code at each step but can't figure out why it isn't working.

Mr. T
  • 11,960
  • 10
  • 32
  • 54
kushaalk
  • 13
  • 2
  • the question has nothing to do with factorial or recurrent functions. Its about `UnboundLocalError: local variable 'factorial' referenced before assignment` which happens when you use undeclared variable. There's a question about that already, so I recommend closing the question. – Kroshka Kartoshka Nov 10 '20 at 13:32

1 Answers1

2

The line factorial = factorial * n refers to a local variable named factorial - which you have never created. So you're using an unbound variable.

It seems you are trying to refer to the factorial in the global scope, outside the function. In that case, you need to declare that using the global keyword

def factorial_recursive(n):
    global factorial
    while n > 1:
        factorial = factorial * n
        factorial_recursive(n - 1)
    return factorial

Keep in mind however, using global variables is almost always a terrible idea.

Why not just get rid of it altogether and accumulatively multiply?

def factorial_recursive(n):
    if n == 1:
        return 1
    return n * factorial_recursive(n - 1)

This is the most common and naive recursive factorial implementation. But it is certainly far better than using global variables.

Chase
  • 5,315
  • 2
  • 15
  • 41