python中写一个求阶乘的函数

您所在的位置:网站首页 python编写程序,定义一个求阶乘的函数 python中写一个求阶乘的函数

python中写一个求阶乘的函数

2024-07-12 20:00| 来源: 网络整理| 查看: 265

 

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)、设置了正确的返回条件 

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3