02.python求和

1.利用循环(for和while)和条件语句实现 

sum1 = 0
for x in range(101):
    sum1 = sum1 + x
print(sum1)

sum = 0
n = 100
while n > 0:
    sum = sum + n
    n = n - 1
print(sum)

等差数列:1.数列公差

                  2.循环次数 

n = int(input())
a=1
sum = 0
for i in range(n):
    sum = a+sum
    a += 1
print(sum)

输出结果:

02.python求和_第1张图片

 

02.python求和_第2张图片

 

2.利用高斯公式求和

(高斯公式,首项加上末项的和乘以项数除以二)

n = int(input())
s = ((1+n)*n/2)
print(s)

02.python求和_第3张图片

3.利用函数实现 

def fun(n):
    sum = 0;
    for i in range(1,n+1):
        sum += i
    return sum

a=fun(100)
print(a)

02.python求和_第4张图片

 

你可能感兴趣的:(numpy)