python 递归、for循环、while循环三种方式求1到100的和

用三种方式:递归,for循环、while循环求1到100的和,三种方式,都采用函数的形式。(楼主用了40多分钟整理测试!)

第一种for循环:

def fsum(n):
    s=0
    for i in range(1,n+1):
        s=s+i
    print(s)
fsum(100)

第二种while循环:

def wsum(n):
    i=0
    s=0
    while (i<n):
        i+=1
        s=s+i
    print(s)
    
wsum(100)

第三种递归:

1 def sum(n):
2     
3     if n==1:
4         return 1
5     return n+sum(n-1)
6   
7 print(sum(100)) #求和,递归最大算到993,再大就报错了,994就死了。

原文地址:https://www.cnblogs.com/bcyczhhb/p/11775339.html