Python Program to Calculate the Sum of All Even Numbers in a List
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)
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:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: Define a list containing integers.even_sum = 0: Initialize a variableeven_sumto store the sum of even numbers.for num in numbers:: Use a for loop to iterate over each element in the list.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.even_sum += num: If the current element is even, add it toeven_sumin.print("列表中所有偶数的和为:", even_sum): Output the sum of all even numbers in the list.
Output result:
列表中所有偶数的和为: 30Other Extensions
Python3 Examples