Project: Standard deviation of ages

Write a class called Person with two private data members: the person's name and age. Its __init__ method takes the two values and stores them. It also has a get_age method.

Then write a separate function, outside the class, called std_dev. It takes a list of Person objects and returns the standard deviation of their ages. Use the population standard deviation, in these steps:

  1. Find the mean age.
  2. For each person, subtract the mean from their age and square the result.
  3. Average those squared gaps (add them up and divide by the number of people).
  4. Take the square root.

To find a standard deviation you need a square root. Raising a number to the power 0.5 gives its square root, so 9 ** 0.5 is 3.0. Python also has a sqrt() function, but it needs an import, which we have not covered.

Here is how the class and function could be used:

person1 = Person("Katie", 73)
person2 = Person("Tran", 24)
person3 = Person("Hanna", 48)
person_list = [person1, person2, person3]
answer = std_dev(person_list)

Save the file as std_dev.py.

Show a solution

Try the project on your own first. This is one working solution, followed by its tests. Press Run to run the tests. Read them to see what thorough testing looks like, then change the solution and run again to watch a test fail.

Projects run on your own computer, so you tell us when you are done.