हिंदी

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

प्रश्न

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

उत्तर

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
  क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
अध्याय 8: Exception Handling & Generate Functions - EXERCISE [पृष्ठ १५८]

APPEARS IN

सीबीएसई Computer Science with Python [English] Class 12
अध्याय 8 Exception Handling & Generate Functions
EXERCISE | Q 13. | पृष्ठ १५८
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×