使用递归函数的阶乘。跟踪代码但无法弄清楚为什么会出现错误
Factorial using recursive functions. Traced the code but cannot figure out why the error is coming
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))
错误信息:
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
我看过使用递归函数求一个数的阶乘的工作代码。我试图自己做,我已经跟踪了每一步的代码,但无法弄清楚为什么它不起作用。
行 factorial = factorial * n
引用名为 factorial
的局部变量 - 您从未创建过。所以你使用的是未绑定变量。
您似乎正试图在函数外部的全局范围内引用 factorial
。在这种情况下,您需要声明使用 global
关键字
def factorial_recursive(n):
global factorial
while n > 1:
factorial = factorial * n
factorial_recursive(n - 1)
return factorial
但是请记住,使用 global
变量几乎总是一个糟糕的主意。
为什么不干脆把它干掉,然后累积成倍数呢?
def factorial_recursive(n):
if n == 1:
return 1
return n * factorial_recursive(n - 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))
错误信息:
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
我看过使用递归函数求一个数的阶乘的工作代码。我试图自己做,我已经跟踪了每一步的代码,但无法弄清楚为什么它不起作用。
行 factorial = factorial * n
引用名为 factorial
的局部变量 - 您从未创建过。所以你使用的是未绑定变量。
您似乎正试图在函数外部的全局范围内引用 factorial
。在这种情况下,您需要声明使用 global
关键字
def factorial_recursive(n):
global factorial
while n > 1:
factorial = factorial * n
factorial_recursive(n - 1)
return factorial
但是请记住,使用 global
变量几乎总是一个糟糕的主意。
为什么不干脆把它干掉,然后累积成倍数呢?
def factorial_recursive(n):
if n == 1:
return 1
return n * factorial_recursive(n - 1)
这是最常见和朴素的递归阶乘实现。但它肯定比使用全局变量要好得多。