I want to return a function which gives the average of all the marks which are 50
or more. When I run my code, it always returns an empty list.
Here is what I have tried:
def get_pass_average(marks):
average = []
for count in marks:
if count >= 50:
average = sum(count) / len(count)
return round(average,2)
def test_get_pass_average():
list1 = [50, 83, 26, 65, 92, 29, 77, 64]
print('%.2f' % (get_pass_average(list1)))
Please help me to figure out the problems in my code, and the output should be 71.83
.
Try this:
l=[i for i in list1 if i>=50]
print(sum(l)/len(l))
Or:
from statistics import mean
l=[i for i in list1 if i>=50]
print(mean(l))
If want to condition for empty lists:
l=[i for i in list1 if i>=50]
if l:
print(sum(l)/len(l))
Or:
from statistics import mean
l=[i for i in list1 if i>=50]
if l:
print(mean(l))
For python 2:
print(sum(l)/len(l))
Should be:
print(float(sum(l))/float(len(l)))
And no statistics module.
Your code doesn't work because you're summing the iterator (an integer) not the list so that's why it's not working
In addition to U9-Forward's answer, one using filter
and mean
:
from statistics import mean
list1 = [50, 83, 26, 65, 92, 29, 77, 64]
average = mean(filter((50).__le__, list1))
print('%.2f' % average)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With