Build a small reusable calculator for basic statistical summaries.
What It Does and Why It Matters
Use the statistics module to compute mean, median, and sample standard deviation. Empty inputs cannot be summarized with mean; sample standard deviation requires at least two values. Keep numerical data separate from formatted presentation.
Use pstdev() for a full population and stdev() for a sample.
Step-by-Step Example
Start with the complete example below. Read the inputs and predict what the final print statement will show before you run it.
from statistics import mean, median, stdev
measurements = [4, 7, 7, 10, 12]
print(mean(measurements))
print(median(measurements))
print(round(stdev(measurements), 2))
How the Code Works
- The imports make these standard-library tools available: statistics.
- The name measurements receives the value of [4, 7, 7, 10, 12]. Changing this input lets you explore a different case.
- The print calls display the results. Compare these results with the method’s documented return type and the input used.
Expected output:
8
7
3.08
Each displayed line comes from the corresponding calculation or check. The output helps verify the return values before you adapt the example to your own input.
What to Notice
Pay attention to the accepted input types, the returned value and the boundary behavior. Predict what changes if you replace the example input with an empty, zero, negative or missing value, where that value is meaningful for this operation.
If the task uses a library function, inspect its documented exceptions and return type before reusing it inside a larger function.
Where You Would Use This
Use the technique when it makes a real task easier to understand or safer to maintain. Check input and output behavior with small tests before combining it with larger application code.
Practice Exercise
Extend the calculator to handle an empty list with a helpful error message.
Before running your edited example, write down the result you expect. Then test at least one valid boundary or deliberately invalid value, using appropriate exception handling where necessary.
Reference: official Python documentation for the complete API contract and version notes.
Common Beginner Mistakes
- Calling stdev() with one measurement or assuming a sample statistic describes an entire population.
- Overlooking the documented condition: empty inputs cannot be summarized with mean; sample standard deviation requires at least two values.
Key Takeaways
- Build a small reusable calculator for basic statistical summaries.
- Use the statistics module to compute mean, median, and sample standard deviation.
- Extend the calculator to handle an empty list with a helpful error message.