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