Python Compute the Sum of All Odd Numbers in a List
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
)
(
"The sum of all odd numbers in the list is:"
,
result
)
Code analysis:
sum_of_oddsThe function takes a listnumbersas its argument.totalThe variable stores the sum of the odd numbers, with an initial value of 0.for num in numbers:The loop iterates over each element in the list.if num % 2 != 0:Check whether the current element is odd (that is, the remainder when divided by 2 is not 0).- If the element is odd, add it to
totalit. - Finally, the function returns
totalvalue. - In the example we define a list containing both odd and even numbers
numbersand call thesum_of_oddsfunction to compute the sum of the odd numbers. printstatement prints the result.
Output result:
列表中所有奇数的和是: 25
Python3 Examples