(1)求1~100的和方法: 方法一:print(sum(range(1,101))) 方法二: sum1 = 0 i = 1 while True: sum1 = sum1 + i if i == 100: break i += 1 print(sum1) 方法三:
(2)
求1~100的偶数和方法:
方法一:
a = 1
sum = 0
while a <= 100:
if a % 2 == 0:
sum += a
a += 1
print(sum)
方法二:
sum1 = 0
for i in range(1,101):
if i % 2 == 0:
sum1 = sum1 +i
i += 1
print("1-100之间偶数的和是:%d" %sum1)
方法三:
#100以内偶数和
c=0
s=[i for i in range(1,101)]
for i in s[1::2]:
c+=i
print c
质数和 i=2 for i in range(2,100): j=2 for j in range(2,i): if i %j ==0: break else: sums3+=i print(sums3)
#偶数和奇数的和 sum1 = 0 sum2 = 0 while i <= 100: if i % 2 == 0: sum1 += i else: sum2 += i i +=1 print("1-100之间偶数和为:%d" % sum1) print("1-100之间奇数和为:%d" % sum2)
#偶数-奇数 j= [] #统计奇数 o= [] #统计偶数 i = 1 while i <=100: if i % 2 == 0:#用来存放偶数 o.append(i) else: j.append(i) i+=1 print j #把所有的奇数放进odd列表中 结果:1,3,5,7,9 print o #把所有的偶数放进even列表中 结果:2,4,,6,8,10 print sum(o) - sum(j)