Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Find the Sum of All Even Numbers in a List

Python Find the Sum of All Even Numbers in a List

Document Object Reference Manual Python3 Examples

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

print

(

"The sum of all even numbers in the list is:"

,

even_sum

)

Code analysis:

  1. numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: Define a list containing integers.
  2. even_sum = 0: Initialize a variable even_sum to store the sum of the 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 == 0 means that if num divided by 2 has a remainder of 0, then num is even.
  5. even_sum += num: If the current element is even, add it to even_sum it.
  6. print("列表中所有偶数的和为:", even_sum): Print the sum of all even numbers in the list.

Output result:

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

Document Object Reference Manual Python3 Examples