Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Compute the Sum from 1 to 100 and the Sum of Its Even Numbers

Python Compute the Sum from 1 to 100 and the Sum of Its Even Numbers

Document Object Reference Manual Python3 Examples

We will write a Python program that computes the sum of all integers from 1 to 100 and prints the sum of all the even numbers among them.

Example

total_sum

=

0

even_sum

=

0

for

i

in

range

(

1

,

101

)

:

    total_sum +

=

i

   

if

i %

2

==

0

:

        even_sum +

=

i

print

(

f

"The sum from 1 to 100 is: {total_sum}"

)

print

(

f

"The sum of all even numbers from 1 to 100 is: {even_sum}"

)

Code analysis:

  1. total_sum and even_sum are used to store the total from 1 to 100 and the even-number sum respectively.
  2. Use for Loop through all integers from 1 to 100.
  3. In each iteration, add the current integer i to total_sum it.
  4. Use if statement checks whether the current integer i is even (i.e., i % 2 == 0); if it is even, add it to even_sum it.
  5. Finally, use print function prints the total sum and the even-number sum.

Output result:

1 到 100 的总和是: 5050
1 到 100 中所有偶数的和是: 2550

Document Object Reference Manual Python3 Examples