我對遞回函式完全陌生,并試圖創建一個函式來計算 n 的階乘。在我的示例中,我假設 n > 0。
def myfactorial(n):
if (n - 1) > 0: # Check if n - 1 is > 0
return ( n * myfactorial(n - 1) ) # Then multiply current n with myfactorial(n - 1)
else:
return # If condition is false, then stop function
但是,它是unsupported operand type(s) for *: 'int' and 'NoneType'該行的錯誤return ( n * myfactorial(n - 1) )。
從w3resource.com查看解決方案時
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
他們在陳述中使用與我相同的回報理念。
誰能告訴我我的方法有什么問題(順便說一句,我故意將 if 陳述句設計為 n-1 > 0,但它也必須與該陳述句一起使用)?
非常感謝您的幫助!
uj5u.com熱心網友回復:
當您撰寫return它時,它的效果與return None.
當你這樣做時myfactorial(1),你回來了None。使用myfactorial(2), 你做2 * myfactorial(1), 這相當于2 * None, 觸發錯誤:
unsupported operand type(s) for *: 'int' and 'NoneType'
這就是為什么你必須寫return 1在你的 else 分支中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/470052.html
