Python Calculate the sum from 1 to 100 and output the sum of even numbers
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}")
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:
total_sumandeven_sumUsed to store the sum from 1 to 100 and the sum of even numbers, respectively.- Use
forLoop through all integers from 1 to 100. - In each loop, the current integer
iis added tototal_sumit. - Use
ifstatement to check whether the current integeriis an even number (i.e.i % 2 == 0), if it is an even number, add it toeven_sumit. - Finally, use
printfunction to output the sum and the sum of even numbers.
Output result:
1 到 100 的总和是: 5050 1 到 100 中所有偶数的和是: 2550Other extensions
Python3 Examples