Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Looping Statements

Sum of even and odd numbers in a list - Python Program

Example 1 :

# Program: Sum of even and odd numbers in a list numbers = list(map(int, input("Enter numbers separated by space: ").split())) sum_even = sum(num for num in numbers if num % 2 == 0) sum_odd = sum(num for num in numbers if num % 2 != 0) print(f"Sum of even numbers: {sum_even}") print(f"Sum of odd numbers: {sum_odd}")

Output

 
OUTPUT  :
Enter numbers separated by space: 1 2 3 4 5 6
Sum of even numbers: 12
Sum of odd numbers: 9 

Explanation

  • Uses list comprehension for filtering.
  • sum_even and sum_odd calculated separately.
  • Works for any length of list.

Example 2 : Advanced Program

def sum_even_odd_in_list(numbers): """ Calculates the sum of even and odd numbers in a list. Args: numbers: A list of integers. Returns: A tuple containing (sum_of_even_numbers, sum_of_odd_numbers). """ even_sum = 0 odd_sum = 0 for num in numbers: if num % 2 == 0: # Check if the number is even even_sum += num else: # The number is odd odd_sum += num return even_sum, odd_sum # Example Usage: my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] sum_even, sum_odd = sum_even_odd_in_list(my_list) print(f"Original List: {my_list}") print(f"Sum of Even Numbers: {sum_even}") print(f"Sum of Odd Numbers: {sum_odd}")

Output

 
OUTPUT  :
Original List: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Sum of Even Numbers: 30
Sum of Odd Numbers: 25

Explanation

  • Uses list comprehension for filtering.
  • sum_even and sum_odd calculated separately.
  • Works for any length of list.

Explanation

sum_even_odd_in_list(numbers) Function:

  • This function takes a list of integers as input.
  • It initializes two variables, even_sumand odd_sum, to zero. These variables will store the cumulative sum of even and odd numbers, respectively.
  • It iterates through each numin the input numbers list using a for
  • Inside the loop, it uses the modulo operator (%) to check if a number is even or odd. If num % 2 == 0, the number is even and is added to even_sum. Otherwise, the number is odd and is added to odd_sum.
  • Finally, the function returns a tuple containing even_sumand odd_sum.