Tuesday, April 4, 2023

Python program to find the sum of all even numbers in a given list of integers

In this program, we define a function called sum_even_numbers that takes a list of integers as an argument. We initialize a variable called sum to 0, and then loop through each number in the input list. For each number, we check if it's even (by checking if the remainder after dividing by 2 is 0). If the number is even, we add it to the sum variable.

# function to find sum of even numbers in a list

def sum_even_numbers(nums):

    sum = 0

    for num in nums:

        if num % 2 == 0:

            sum += num

    return sum

# example usage

my_list = [2, 3, 6, 8, 10]

print(sum_even_numbers(my_list))

# output: 26

Finally, we return the sum variable as the output of the function. In the example usage, we create a list called my_list and pass it to the sum_even_numbers function. The function returns 26, which is the sum of all even numbers in the list [2, 3, 6, 8, 10].

No comments:

Post a Comment

CBSE Admit Cards 2025: Class 10 & 12 Hall Tickets - Download Now & Prepare for Exams!

The Central Board of Secondary Education (CBSE) is gearing up to release the admit cards for the highly anticipated Class 10 and Class 12 bo...