python中寫一個求階乘的函數


 

1、利用迭代

def fun(n): ## 定義求階乘函數 result = 1
    for i in range(1,n + 1): result *= i return result n = int(input("please input the number:")) ## 指定用戶輸入 result = fun(n) print("%d的階乘是:%d" % (n,result))        ## 輸出結果
please input the number:4 4的階乘是:24

 

2、遞歸

遞歸:從原理上來說就是函數調用自身的行為。在函數內部可以調用所有可見的函數,當然也包括它自己。

def fun(n): if n == 1: ## 終止信號(返回條件) return 1
    else: return n * fun(n - 1) ## 調用函數本身 n = int(input("please input the number:")) result = fun(n) print("%d 的階乘是:%d" % (n,result))
please input the number:3
3 的階乘是:6

 

遞歸的兩個條件:

(1)、調用函數本身

(2)、設置了正確的返回條件 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM