阶乘的递归函数

时间:2018-10-30 01:31:13

标签: python-3.x recursion

我正在编写此代码以获取10! ,但是,我相信我在其中有一个无限循环,因为它不断重复相同的错误代码。我正在尝试查找问题,但似乎找不到。

def calculatingfactor(num2cal):
  """this fuction will be calculating a mathematical factorial"""
  if num2cal == 1:
    returnvalue = 1
  elif num2cal <= 0:
    returnvalue = 0
  else:
    print("Calculating the facterial of {}".format(num2cal))
    variable2 = calculatingfactor(num2cal - 1)
    returnvalue = calculatingfactor(num2cal*variable2)
    return 

#main code
first_fact=calculatingfactor(10)
print (first_fact)

1 个答案:

答案 0 :(得分:1)

您的代码的递归情况对我来说似乎不正确。您应该在将num2cal递减1的情况下调用同一函数,然后返回当前值乘以递归调用返回的值。

def calculatingfactor(num2cal):
  if num2cal == 1:
    return 1
  elif num2cal <= 0:
    return 0
  else:
    print("Calculating the facterial of {}".format(num2cal))
    variable2 = calculatingfactor(num2cal - 1)
    return num2cal*variable2 

# main code
first_fact=calculatingfactor(10)
print (first_fact)