Exercise 27

Write Python program with two functions - sum_list() and multiply_list() - that calculate the sum and product of elements in a given list of numbers.

Solution

def sum_list(numbers):
    """
    Calculate the sum of elements in a list of numbers.
    """
    total = 0
    for num in numbers:
        total += num
    return total
def multiply_list(numbers):
    """
    Calculate the product of elements in a list of numbers.
    """
    product = 1
    for num in numbers:
        product *= num
    return product





To use these functions, you can call them and pass in a list of numbers as an argument. Here's an example:

my_list = [1, 2, 3, 4, 5]
print(sum_list(my_list)) # Output: 15
print(multiply_list(my_list)) # Output: 120

Explanation:

  1. We create a list 'mylist': in order to test the two functions sum_list function() and multiply_list function()
  2. In the first example, sum_list function(): is called with my_list as an argument, which returns the sum of all the elements in the list. The output is 15.
  3. In the second example, multiply_list function(): is called with my_list as an argument, which returns the product of all the elements in the list. The output is 120.

 

Younes Derfoufi
my-courses.net

One thought on “Solution Exercise 27 : Program python to compute the sum and the product of given list”

Leave a Reply