pythonbeginner10 minutes

Sum All Odd Numbers in a List

Write a function that calculates the sum of all odd numbers in a given list of integers.

Challenge prompt

Create a function called sum_odd_numbers that takes a list of integers as input and returns the sum of all the odd numbers in the list. If there are no odd numbers, the function should return 0.

Guidance

  • Iterate through each number in the list to check if it is odd.
  • Use the modulus operator (%) to determine whether a number is odd.
  • Keep a running total of all odd numbers encountered.
  • Return the total after processing the entire list.

Hints

  • Recall that an odd number has a remainder of 1 when divided by 2 (number % 2 == 1).
  • Start by initializing a variable (like total) to 0 to accumulate the sum.
  • You can use a for loop to go through all elements in the list.

Starter code

def sum_odd_numbers(numbers):
    # Initialize the sum
    total = 0
    # Your code here
    return total

Expected output

sum_odd_numbers([1, 2, 3, 4, 5]) -> 9 sum_odd_numbers([2, 4, 6, 8]) -> 0 sum_odd_numbers([7, 11, 13]) -> 31

Core concepts

loopsconditional statementsfunctionsmodulus operator

Challenge a Friend

Send this duel to someone else and see if they can solve it.