Python Compute the Sum from 1 to 100 and the Sum of Its Even Numbers
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
(
f
"The sum from 1 to 100 is: {total_sum}"
)
(
f
"The sum of all even numbers from 1 to 100 is: {even_sum}"
)
Code analysis:
total_sumandeven_sumare used to store the total from 1 to 100 and the even-number sum respectively.- Use
forLoop through all integers from 1 to 100. - In each iteration, add the current integer
itototal_sumit. - Use
ifstatement checks whether the current integeriis even (i.e.,i % 2 == 0); if it is even, add it toeven_sumit. - Finally, use
printfunction prints the total sum and the even-number sum.
Output result:
1 到 100 的总和是: 5050
1 到 100 中所有偶数的和是: 2550
Python3 Examples