python实现求阶乘

"""
求阶乘
计算阶乘 n! = 1*2*3...*n
"""


def jiecheng(n):
    if n < 0 or type(n) != int:
        raise TypeError("n must type int and n > 0")

    if n == 0:
        return 1

    return n * jiecheng(n - 1)


def jiecheng02(n):
    if n < 0 or type(n) != int:
        raise TypeError("n must type int and n > 0")

    result = 1
    s = 1
    while s <= n:
        result *= s
        s += 1
    return result


if __name__ == '__main__':
    result = jiecheng(5)
    print(result)
    aresult = jiecheng02(5)
    print(aresult)
发布了45 篇原创文章 · 获赞 9 · 访问量 2247

猜你喜欢

转载自blog.csdn.net/adsszl_no_one/article/details/105315466