如何在 Python 中使用遞迴找出數字的階乘?


數字的階乘是從 1 至該數字的所有數字的乘積。

如果函式呼叫自身,則稱該函式為遞迴函式。

在以下程式中,factorial() 函式接受一個引數,並不斷呼叫自身,將值減少 1,直到達到 1 為止。

示例

def factorial(x):
    if x==1:
        return 1
    else:
        return x*factorial(x-1)

f=factorial(5)
print ("factorial of 5 is ",f)

輸出

結果是

factorial of 5 is  120


更新於:21-Feb-2020

721 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.