Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
What does statistics.mean([]) do? Write safe_mean(values) that gives None for an empty list and the mean otherwise.
Catch the specific error that you expect.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, compare your working with the solution.
An empty list has no mean, so statistics.mean([]) raises a StatisticsError ("mean requires at least one data point").
safe_mean([4, 6, 8]) is , and safe_mean([]) is None. We catch the specific error. A bare except: would also hide real bugs.
Log in to join the discussion.
Loading…