Python Mean, Median, Mode & Variance Program for CBSE AI Board Practicals

⚡ Direct Answer & Key Takeaway

The CBSE AI Practical exam carries 50 marks (including Python programs, practical file, capstone project, and viva voce), and descriptive statistics is a staple lab task across Code 417 and Code 843. To compute Mean, Median, Mode, and Population Variance cleanly without external dependencies, write both standard-library statistics calls and explicit loop-based formulas: mean = sum(x) / n, sorted midpoint for median, frequency dictionary for mode, and variance = sum((xi - mean)^2) / n.

1. Manual Loop Formulas vs Python's Built-In statistics Module

During board practicals, external examiners often ask students to implement statistical metrics without relying solely on black-box libraries so they can verify algorithmic thinking. Python's built-in statistics module provides mean(), median(), mode(), pvariance(), and variance(), which are ideal for validating results in Data Science units. However, writing custom functions using sorted(), len(), sum(), and dictionaries proves you understand edge cases—such as averaging the two middle elements when a dataset has an even length, or handling ties in mode computation. Also distinguish population variance (dividing squared deviations by n, matching statistics.pvariance) from sample variance (dividing by n - 1, matching statistics.variance and Bessel's correction). Knowing which denominator your practical rubric expects prevents a subtle off-by-one discrepancy during viva verification.

  • Use sorted(data) instead of data.sort() inside custom functions to avoid mutating the caller's list.
  • Check n % 2 == 1 for odd-length medians (index n // 2) versus averaging indices n // 2 - 1 and n // 2.
  • Clarify whether the lab sheet expects population variance (divide by n) or sample variance (divide by n - 1).

2. Tracing Variance & Standard Deviation on Sample Exam Scores

Consider a crisp 6-element dataset representing student AI quiz scores: [12, 15, 15, 18, 20, 22]. First, calculate the sum: 12 + 15 + 15 + 18 + 20 + 22 = 102, giving a mean of 102 / 6 = 17.0. Because the sorted list has six items (even count), the median averages the third and fourth values: (15 + 18) / 2 = 16.5, while the mode is 15 since it appears twice. Next, compute each squared deviation (x - 17)^2: 25, 4, 4, 1, 9, and 25, summing to 68. Dividing 68 by n = 6 yields a population variance of 11.3333 (and standard deviation sqrt(11.3333) = 3.37), whereas dividing by n - 1 = 5 yields a sample variance of 13.60.

  • Verify squared deviations first: any negative sign disappears once (x - mean) is squared.
  • Keep standard deviation in mind as math.sqrt(variance), which shares the original data's unit.
  • Detect outliers early: a single extreme value inflates mean and variance far more than median.

3. Writing Clean Practical Files That Impress External Examiners

A CBSE AI practical submission is graded not only on final output, but also on readability, modularity, and dry-run verification. Organize your script into single-purpose helper functions, wrap test data cleanly, and format printed floats to two or four decimal places with f-strings so results match hand-calculated tables. Avoid installing third-party packages like SciPy on restricted school lab machines where internet access is disabled; standard Python 3 libraries (statistics and math) run on every system out of the box. In Code 843 Class 11–12 projects, the same variance and standard deviation logic underpins Z-score standardization and RMSE regression evaluation, making this foundational script directly reusable across your capstone notebook and board practical file.

  • Zero external packages needed: Python's standard math and statistics modules run offline on all lab PCs.
  • Format outputs cleanly (e.g., {val:.2f}) and echo input data so screenshots in your practical file are self-explanatory.
  • Practice tracing each squared-deviation row by hand to answer viva follow-ups confidently.

4. Standalone Mean, Median, Mode & Variance Calculator (Zero External Deps)

import math
import statistics

scores = [12, 15, 15, 18, 20, 22]

def calc_mean(data):
    return sum(data) / len(data)

def calc_median(data):
    s = sorted(data)
    n = len(s)
    mid = n // 2
    if n % 2 == 1:
        return s[mid]
    return (s[mid - 1] + s[mid]) / 2

def calc_mode(data):
    freq = {}
    for x in data:
        freq[x] = freq.get(x, 0) + 1
    max_freq = max(freq.values())
    return [k for k, v in freq.items() if v == max_freq]

def calc_variance(data, sample=False):
    mu = calc_mean(data)
    sq_diff = sum((x - mu) ** 2 for x in data)
    denom = (len(data) - 1) if sample else len(data)
    return sq_diff / denom

mean_val = calc_mean(scores)
median_val = calc_median(scores)
mode_val = calc_mode(scores)
pop_var = calc_variance(scores, sample=False)
samp_var = calc_variance(scores, sample=True)
pop_std = math.sqrt(pop_var)

print("Data:", scores)
print(f"Mean: {mean_val:.2f} | stdlib: {statistics.mean(scores):.2f}")
print(f"Median: {median_val:.2f} | stdlib: {statistics.median(scores):.2f}")
print(f"Mode: {mode_val} | stdlib: {statistics.mode(scores)}")
print(f"Pop Variance: {pop_var:.4f} | stdlib: {statistics.pvariance(scores):.4f}")
print(f"Sample Variance: {samp_var:.4f} | stdlib: {statistics.variance(scores):.4f}")
print(f"Pop Std Dev: {pop_std:.4f}")

Verified Console / Dry-Run Output:

Data: [12, 15, 15, 18, 20, 22]
Mean: 17.00 | stdlib: 17.00
Median: 16.50 | stdlib: 16.50
Mode: [15] | stdlib: 15
Pop Variance: 11.3333 | stdlib: 11.3333
Sample Variance: 13.6000 | stdlib: 13.6000
Pop Std Dev: 3.3665

5. Dry-Run Calculation Table for Scores [12, 15, 15, 18, 20, 22]

Observation (x)Deviation (x - 17)Squared Deviation (x - 17)^2FrequencyRunning Sum of Squares
12-525125
15-242 (first)29
15-242 (second)33
18+11134
20+39143
22+525168 (Total -> Var = 68/6 = 11.33)
🎯 1-on-1 Live Mentorship & Free Study Kit

Code & Dry-Run AI Practicals 1-on-1

Master Python statistics, NumPy, and CBSE Class 10 & 12 board practicals with live code review in a free 1:1 session or 1:4 Micro-Pod at 4Achievers Junior.

💬 WhatsApp Now
🔒 Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Using data.sort() in-place without sorting first or mutating the original list before printing.
  • Avoid Mistake: Forgetting to divide by n - 1 when specifically asked for sample variance instead of population variance.
  • Avoid Mistake: Computing median on an unsorted list, which picks an arbitrary element instead of the true middle value.
  • Avoid Mistake: Using statistics.mode() on older Python versions when data is bimodal without handling ties.
  • Examiner / Mentor Tip: Know why variance squares deviations: positive and negative deviations would otherwise cancel to zero.
  • Examiner / Mentor Tip: Be ready to explain why Median beats Mean when data contains extreme outliers (like one 100 among 10s).
  • Examiner / Mentor Tip: Remember that Standard Deviation is the square root of Variance and returns to the original unit.

7. Interactive Concept Check Quiz

Question: For the dataset [4, 6, 8, 10], what is the Population Variance (dividing by n)?

8. Frequently Asked Questions

When should I use statistics.pvariance() vs statistics.variance() in Python?
Use pvariance() when your list represents the entire population (divides by n) and variance() when it is a sample from a larger group (divides by n - 1).
Can I write the practical exam program without NumPy or Pandas?
Yes. CBSE Code 417 statistics programs work cleanly with standard Python loops, math, and the built-in statistics module, avoiding installation issues on lab machines.
What happens if a dataset has no repeated values when finding Mode?
A dictionary-based mode helper returns all unique elements tied at frequency 1, whereas in statistics it is better to report 'no unique mode' if max frequency equals 1.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class