Python Find 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 use a simple for loop to iterate over the list and 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
Print the sum of the even numbers
(
"The sum of all even numbers in the list is:"
,
even_sum
)
Code analysis:
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 the 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 == 0means that ifnumdivided by 2 has a remainder of 0, thennumis even.even_sum += num: If the current element is even, add it toeven_sumit.print("列表中所有偶数的和为:", even_sum): Print the sum of all even numbers in the list.
Output result:
列表中所有偶数的和为: 30
Python3 Examples