Python Calculate the Sum of All Odd Numbers in a List

Document 对象参考手册Python3 Examples

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)

Code analysis:

  1. sum_of_oddsThe function accepts a listnumbersas a parameter.
  2. totalThe variable is used to store the total sum of odd numbers, with an initial value of 0.
  3. for num in numbers:The loop iterates through each element in the list.
  4. if num % 2 != 0:Check whether the current element is odd (i.e., the remainder when divided by 2 is not 0).
  5. If the element is odd, add it tototalin.
  6. Finally, the function returnstotalthe value of.
  7. In the example, we define a list containing odd and even numbersnumbers, and callsum_of_oddsthe function to calculate the sum of odd numbers.
  8. printThe statement outputs the result.

Output result:

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

Document 对象参考手册Python3 Examples

Other extensions