python uses while to find the sum of integers within 100
- 2021-12-12 08:55:43
- OfStack
The sum of 1, 1 to 100
Define 2 variables i and
sum
The initial values are all 1, the value of i is increased by 1 every time, and the program is finished after taking 100.
sum
Is equal to itself plus the value of i. Thus i is fetched from 2 to 100 and added to sum each time.
#!/usr/bin/env python
#-*- coding:utf-8 -*-
i=1
sum=1
while True:
i+=1
sum=sum+i
if i==100:
break
print(sum)
2, even sums from 1 to 100
Method 1: Same as above, except that the initial values of i and sum are 0, and the values of i are increased by 2 every time, and the program ends after taking 100.
#!/usr/bin/env python
#-*- coding:utf-8 -*-
i=0
sum=0
while True:
i+=2
sum=sum+i
if i==100:
break
print(sum)
Method 2: Make num% 2 by taking the cofunction%, and if it is equal to 0, it is even, sum=sum+num
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Python Learning and communication group: 778463939
num=0
sum=0
while True:
num+=1
if num%2==0:
sum=sum+num
if num==100:
break
print("Task finished!The sum of even numbers from 1 to 100 is: "+str(sum))
Little knowledge: The equal sign is = =, which can no longer be written as num% 2=0.
3, odd sums from 1 to 100
Method 1: Same as above, except that the initial value of i and sum is 1, and the value of i is increased by 2 every time. The value of i, which needs special attention here, ends after 99, otherwise the program is dead loop.
#!/usr/bin/env python
#-*- coding:utf-8 -*-
i=int(1)
sum=int(1)
while True:
i+=2
sum=sum+i
if i==99:
break
print(sum)
Method 2: Make num% 2 by taking the cofunction%, and if it is equal to 1, it is odd, sum=sum+num
#!/usr/bin/env python
# -*- coding:utf-8 -*-
num=0
sum=0
while True:
num+=1
if num%2==1:
sum=sum+num
if num==100:
break
print("Task finished!The sum of odd numbers from 1 to 100 is: "+str(sum))