用Python写出求和函数,阶乘函数_Python笔记源码

用Python写出求和函数,阶乘函数_Python笔记源码

用Python写出求和函数,阶乘函数_Python笔记源码

  1. 写一个函数mysum(n),要求给出一个数n,求 

     1 + 2 +3 + 4 + ..... + n 的和

    如:

      print(mysum(100))  # 5050

      print(mysum(10))  # 55

代码:

def mysum(n):

s = 0

for i in range(1,n+1):

s += i

return s


  2. 写一个函数myfac(n)来计算n!(n的阶乘)

    n! = 1*2*3*4*....*n

    如:

      print(myfac(5))  # 120

      print(myfac(4))  # 24

代码:

def myfac(n):

s = 1

for i in range(2,n+1):

s *= i

return s


  3. 写一个函数,求

      1 + 2**3 + 3**3 + ... + n**n的和

      (n给个小点的数)

代码:

def mycc(n):

s = 0

for i in range(1,n+1):

s += i**i

return s


最后编辑于:2019/09/26作者: 牛逼PHP

发表评论