Python uses while to find the integer sum within 100

Time:2022-5-6
catalogue
  • 1. Sum of 1 to 100
  • 2. Even sum from 1 to 100
  • 3. Odd sum from 1 to 100

1. Sum of 1 to 100

Define 2 variables I andsum, the initial value is 1, and the value of I increases by 1 every time. After taking 100, the program ends,sumThe value of is equal to itself plus the value of I. In this way, I is taken from 2 to 100 and added to sum every time.

?
1
2
3
4
5
6
7
8
9
10
#!/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 sum from 1 to 100

Method 1:The same as above, except that the initial value of I and sum is 0, and the value of I increases by 2 every time. After taking 100, the program ends.

?
1
2
3
4
5
6
7
8
9
10
#!/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:By taking the remainder function%, let num% 2. If it is equal to 0, it will be an even number, sum = sum + num

?
1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#Python learning exchange 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))

Tips:The equals sign is = =, which can no longer be written as num% 2 = 0.

3. Odd sum from 1 to 100

Method 1:The same as above, except that the initial value of I and sum is 1, and the value of I increases by 2 every time. Here, we need to pay special attention to that the program ends after the value of I reaches 99, otherwise the program will loop.

?
1
2
3
4
5
6
7
8
9
10
#!/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:By taking the remainder function%, let num% 2. If it is equal to 1, it will be an odd number, sum = sum + num

?
1
2
3
4
5
6
7
8
9
10
11
#!/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))

This is the end of this article about how Python uses while to find integers within 100. For more information about Python using while to find integers within 100, please search for previous articles on developeppaper or continue to browse the relevant articles below. I hope you will support developeppaper in the future!

Recommended Today

How to read a source code?

The ability to read source code is one of the underlying basic abilities of programmers. The reason why this ability is important is: Inevitably, you need to read or take over other people’s projects. For example, research an open source project, such as taking over a project of others. Reading excellent project source code is […]