+ 1

ZeroDivisionError for a list

"Write a function named mean that accepts a list of numbers as a parameter and returns the arithmetic mean (average) of the numbers in the list as a number. For example, if the list passed contains [2.0, 4.5, 6.5, 1.0], your function should return 3.5. If the list is empty, return 0.0. Do not modify the list that is passed in." This is my code which works for any list of numbers except for when the list is blank ([]) it doesn't return zero, i just get a "ZeroDivisionError"... def mean(list): a = list b = sum(a) count = 0 for i in range(len(list)): count += 1 if a == '': average = 0.0 return average average = b / count return average How do I get the code to output 0.0 if a blank list is inputted?

24th Mar 2018, 1:41 AM
Taylor Deal
Taylor Deal - avatar
3 Réponses
+ 1
You get that error because if the list is empty the statement count += 1 is never executed. So, you end up doing average = b / 0 (count was initialized to 0) One way to fix this is to check if the list is empty and do what must be done before getting to the loop
24th Mar 2018, 2:10 AM
cyk
cyk - avatar
+ 1
Also, is your list a String? By doing a == '', you are treating it as a String... If it is a list, you are better off doing len(a) == 0 to check if it is empty
24th Mar 2018, 2:16 AM
cyk
cyk - avatar
+ 1
Here. Take a look at the code and read the comments :) https://code.sololearn.com/ck8NpoN2CYnw/?ref=app
24th Mar 2018, 2:24 AM
cyk
cyk - avatar