Python Program to Calculate the Sum of All Even Numbers in a List

Document 对象参考手册Python3 Examples

We will write a Python program to find the sum of all even numbers in a list. We will use a simple for loop to iterate over the list, and use a conditional statement to check whether each element is even.

Example

# Define a list containing integers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Initialize a variable to store the sum of even numbers
even_sum = 0

# Iterate over each element in the list
for num in numbers:
    # Check whether the current element is even
    if num % 2 == 0:
        # If it is even, add it to even_sum
        even_sum += num

# Output the sum of even numbers
print(The sum of all even numbers in the list is:, even_sum)

Code explanation:

  1. numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: Define a list containing integers.
  2. even_sum = 0: Initialize a variableeven_sumto store the sum of even numbers.
  3. for num in numbers:: Use a for loop to iterate over each element in the list.
  4. if num % 2 == 0:: Use a conditional statement to check whether the current element is even.num % 2 == 0indicates that ifnumthe remainder when divided by 2 is 0, thennumit is even.
  5. even_sum += num: If the current element is even, add it toeven_sumin.
  6. print("列表中所有偶数的和为:", even_sum): Output the sum of all even numbers in the list.

Output result:

列表中所有偶数的和为: 30

Document 对象参考手册Python3 Examples

Other Extensions