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

Python Compute the Sum of All Odd Numbers in a List

Python Compute the Sum of All Odd Numbers in a List

Document Object Reference Manual Python3 Examples

We will write a Python program to compute the sum of all odd 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 odd. If it is odd, add it to the total.

Example

def

sum_of_odds

(

numbers

)

:

    total

=

0

   

for

num

in

numbers:

       

if

num %

2

!=

0

:

            total +

=

num

   

return

total

Example list

numbers

=

[

1

,

2

,

3

,

4

,

5

,

6

,

7

,

8

,

9

]

result

=

sum_of_odds

(

numbers

)

print

(

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

,

result

)

Code analysis:

  1. sum_of_odds The function takes a list numbers as its argument.
  2. total The variable stores the sum of the odd numbers, with an initial value of 0.
  3. for num in numbers: The loop iterates over each element in the list.
  4. if num % 2 != 0: Check whether the current element is odd (that is, the remainder when divided by 2 is not 0).
  5. If the element is odd, add it to total it.
  6. Finally, the function returns total value.
  7. In the example we define a list containing both odd and even numbers numbersand call the sum_of_odds function to compute the sum of the odd numbers.
  8. print statement prints the result.

Output result:

列表中所有奇数的和是: 25

Document Object Reference Manual Python3 Examples