Python Calculate the sum from 1 to 100 and output the sum of even numbers

Document 对象参考手册Python3 Examples

We will write a Python program to calculate the sum of all integers from 1 to 100, and output the sum of all even numbers.

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_sumandeven_sumUsed to store the sum from 1 to 100 and the sum of even numbers, respectively.
  2. UseforLoop through all integers from 1 to 100.
  3. In each loop, the current integeriis added tototal_sumit.
  4. Useifstatement to check whether the current integeriis an even number (i.e.i % 2 == 0), if it is an even number, add it toeven_sumit.
  5. Finally, useprintfunction to output the sum and the sum of even numbers.

Output result:

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

Document 对象参考手册Python3 Examples

Other extensions