python中for、while语句计算1-100的和。
1、for语句
1-100的和
>>> sum = 0
>>> for i in range(1,101):
sum += i
>>> print(sum)
5050
>>>
1-100内偶数的和
>>> sum = 0
>>> for i in range(101):
if i % 2 == 0:
sum += i
>>> print(sum)
2550
2、while语句
方法1:
>>> sum = 0
>>> i = 100
>>> while i > 0:
sum += i
i = i - 1
>>> print(sum)
5050
方法2:
>>> i = 1
>>> j = 100
>>> sum = 0
>>> while i <= j:
sum += i
i += 1
>>> print(sum)
5050