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.