Skip to content

Data Analyzer

Easy ~20 min

What you'll build

A Python script that takes a list of numbers and computes mean, median, mode, min, max, and standard deviation, then prints a formatted report.

Goals

  • Use the statistics module for mean, median, mode
  • Compute min, max, and range manually
  • Format output with f-strings and alignment
  • Handle empty lists gracefully

Prerequisites

  • Lists and list methods
  • Functions with parameters
  • Importing modules

Steps

  1. 1

    Import statistics and define the analyzer

    Import the statistics module and define analyze(data) that takes a list of numbers. Guard against empty lists by returning early with a message.

    Code
    import statistics
    
    def analyze(data):
        if not data:
            return "No data to analyze"
        results = {}
        results["count"] = len(data)
        results["mean"] = statistics.mean(data)
        results["median"] = statistics.median(data)
        return results

    Expected result

    analyze([1, 2, 3, 4, 5]) returns a dict with count, mean, and median.

  2. 2

    Add more statistics

    Extend the function to compute min, max, range, and standard deviation. Use try/except for mode since it can raise StatisticsError for multimodal data.

    Code
        results["min"] = min(data)
        results["max"] = max(data)
        results["range"] = max(data) - min(data)
        results["stdev"] = statistics.stdev(data) if len(data) > 1 else 0
        try:
            results["mode"] = statistics.mode(data)
        except statistics.StatisticsError:
            results["mode"] = "no unique mode"

    Expected result

    The results dict now includes min, max, range, stdev, and mode.

  3. 3

    Print the formatted report

    Print each statistic with a label, aligned using f-string width specifiers. Call analyze with sample data and print the results.

    Code
    def print_report(data):
        results = analyze(data)
        if isinstance(results, str):
            print(results)
            return
        print("=== Data Analysis Report ===")
        for key, value in results.items():
            print(f"{key:>10}: {value}")
    
    print_report([10, 20, 20, 30, 40, 50])

    Expected result

    A formatted report showing count, mean, median, min, max, range, stdev, and mode.

  4. 4

    Add input validation & exception handling

    Add a try/except block in the main function to handle user input errors, using ValueError to catch illegal conversions. Python's exception handling lets the program degrade gracefully on bad input instead of crashing.

    Code
    def safe_input(prompt, validator=None):
        """Read input with validation and error handling."""
        while True:
            try:
                raw = input(prompt)
                value = float(raw)
                if validator and not validator(value):
                    raise ValueError(f"Value {value} failed validation")
                return value
            except ValueError as err:
                print(f"Invalid input: {err}. Please try again.")
    
    # Usage
    age = safe_input("Enter your age: ", lambda x: x > 0)

    Expected result

    Invalid input (non-number or failed validation) prompts for re-entry; valid input returns the number.

  5. 5

    Write unit tests

    Write tests for the core function using unittest or assert statements, covering normal paths, boundary values, and exceptions. Tests are the safety net for code quality.

    Code
    import unittest
    
    class TestCoreFunc(unittest.TestCase):
        def test_normal(self):
            self.assertEqual(core_func(5), expected_5)
    
        def test_boundary(self):
            self.assertEqual(core_func(0), expected_0)
    
        def test_exception(self):
            with self.assertRaises(ValueError):
                core_func(-1)
    
    if __name__ == "__main__":
        unittest.main()

    Expected result

    Running python test.py prints OK with all three test cases passing.

Try it yourself

What you learned

You used the statistics module, handled edge cases (empty lists, multimodal data), and formatted output — the foundation of data analysis scripts.

Related Resources

Related Lessons

  • Lists

    List operations for data.

  • Modules

    Using the statistics module.

Related Practice

Related Cheatsheets

Related Errors

Related Glossary

Related Glossary

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

Related Errors

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

← Back to topic