English

Write a function to find average of a list of numbers. Your function should be able to handle an empty list and also list containing string.

Advertisements
Advertisements

Question

Write a function to find average of a list of numbers. Your function should be able to handle an empty list and also list containing string.

Code Writing
Advertisements

Solution

The following function converts numeric strings such as "20" to numbers and ignores non-numeric values. It returns None when no valid numbers are present.

def average(values):
    numbers = []

    for value in values:
        try:
            numbers.append(float(value))
        except (TypeError, ValueError):
            # Ignore values that cannot be converted to numbers.
            continue

    if not numbers:
        return None

    return sum(numbers) / len(numbers)


print(average([10, 20, "30"]))       # 20.0
print(average([10, "hello", 20]))    # 15.0
print(average([]))                    # None

Returning None clearly indicates that an average cannot be calculated for an empty or completely invalid list.

shaalaa.com
  Is there an error in this question or solution?
Chapter 8: Exception Handling & Generate Functions - EXERCISE [Page 158]

APPEARS IN

CBSE Computer Science with Python [English] Class 12
Chapter 8 Exception Handling & Generate Functions
EXERCISE | Q 13. | Page 158
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×