Python Calculate the Sum of All Odd Numbers in a List
We will write a Python program to calculate the sum of all odd numbers in a list. We will use a simple for loop to iterate through the list and use a conditional statement to check whether each element is odd. If it is odd, add it to the total sum.
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)
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:
sum_of_oddsThe function accepts a listnumbersas a parameter.totalThe variable is used to store the total sum of odd numbers, with an initial value of 0.for num in numbers:The loop iterates through each element in the list.if num % 2 != 0:Check whether the current element is odd (i.e., the remainder when divided by 2 is not 0).- If the element is odd, add it to
totalin. - Finally, the function returns
totalthe value of. - In the example, we define a list containing odd and even numbers
numbers, and callsum_of_oddsthe function to calculate the sum of odd numbers. printThe statement outputs the result.
Output result:
列表中所有奇数的和是: 25Other extensions
Python3 Examples