15 Python Programs for Class 10 AI Practical File (CBSE 2025-26)

Class 10 AI Python practicals feel overwhelming the first time you see libraries like NumPy, Matplotlib, and OpenCV. This page cuts through that — every program you need for your practical file, written cleanly, with output shown and each line explained.

All programs here are aligned to CBSE AI Class 10 (Subject Code 417), Unit 7: Advance Python, 2025-26 syllabus. Unit 7 is assessed through practicals only — there are no theory marks for this unit.

What You’ll Learn

  • All 8 programs from the CBSE Class 10 suggested list, with complete code and output
  • 7 additional programs covering the same libraries — for a complete, exam-ready practical file
  • How to set up Jupyter Notebook before running these programs
  • What to write in your practical file for each program

Before You Start

Libraries you need for Class 10:

  • numpy — numerical calculations
  • matplotlib — charts and graphs
  • pandas — reading and working with CSV files
  • cv2 (OpenCV) — reading and working with images

All of these come pre-installed with Anaconda. If you haven’t set up Jupyter Notebook yet, follow our Jupyter Notebook Setup & Installation Guide first, then come back here.

Practical file formatting rule: Every program must have a comment header. Every program must show the expected output. Use the format shown in each program below.

📌 Class 10 Note: Unit 7 (Advance Python) carries no theory marks. Your Python performance is entirely in the practical examination (20 marks). Run every program yourself and note the output — don’t just copy code without understanding what it does.


Section 1 — NumPy Programs (Programs 1–3)


Program 1: Add Elements of Two Lists ✅ CBSE Suggested

python

# Program to add the elements of two lists

import numpy as np

list1 = [10, 20, 30, 40, 50]
list2 = [5, 15, 25, 35, 45]

arr1 = np.array(list1)
arr2 = np.array(list2)

result = arr1 + arr2

print("List 1:", list1)
print("List 2:", list2)
print("Sum of elements:", result)

Expected Output:

List 1: [10, 20, 30, 40, 50]
List 2: [5, 15, 25, 35, 45]
Sum of elements: [15 35 55 75 95]

How it works: NumPy adds lists element by element — index 0 with index 0, index 1 with index 1, and so on. This is called element-wise addition. Regular Python lists cannot do this directly; NumPy makes it one line.


Program 2: Calculate Mean, Median and Mode ✅ CBSE Suggested

python

# Program to calculate mean, median and mode using NumPy

import numpy as np
from scipy import stats

data = [15, 20, 35, 40, 50, 20, 15, 20, 30, 25]

mean   = np.mean(data)
median = np.median(data)
mode   = stats.mode(data, keepdims=True)

print("Data:", data)
print("Mean  :", mean)
print("Median:", median)
print("Mode  :", mode.mode[0])

Expected Output:

Data: [15, 20, 35, 40, 50, 20, 15, 20, 30, 25]
Mean  : 27.0
Median: 22.5
Mode  : 20

What each measure tells you:

MeasureFormulaWhat It Shows
MeanSum ÷ CountAverage value
MedianMiddle value when sortedCentre of the data
ModeMost frequent valueMost common value

Program 3: NumPy Array — Basic Statistical Operations

python

# Program to perform basic statistical operations on a NumPy array

import numpy as np

marks = np.array([72, 85, 91, 68, 78, 95, 88, 74, 82, 79])

print("Marks Array:", marks)
print("Maximum Marks:", np.max(marks))
print("Minimum Marks:", np.min(marks))
print("Mean Marks  :", np.mean(marks))
print("Sum of Marks:", np.sum(marks))
print("Standard Deviation:", round(np.std(marks), 2))

Expected Output:

Marks Array: [72 85 91 68 78 95 88 74 82 79]
Maximum Marks: 95
Minimum Marks: 68
Mean Marks  : 81.2
Sum of Marks: 812
Standard Deviation: 7.97

Why this matters: In AI, before you train any model, you always check these basic statistics on your dataset to understand its shape and spread. This step is called Exploratory Data Analysis (EDA).


Section 2 — Matplotlib Programs (Programs 4–7)


Program 4: Display a Line Chart ✅ CBSE Suggested

python

# Program to display a line chart from (2,5) to (9,10)

import matplotlib.pyplot as plt

x = [2, 9]
y = [5, 10]

plt.plot(x, y, color='blue', marker='o', linewidth=2)
plt.title("Line Chart")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.grid(True)
plt.show()

Expected Output: A blue line connecting the points (2, 5) and (9, 10), with dots at each point.

Key parameters explained:

  • color='blue' — sets the line colour
  • marker='o' — adds a circular dot at each data point
  • linewidth=2 — makes the line thicker
  • plt.grid(True) — adds a background grid (makes the chart easier to read)

Program 5: Display a Scatter Chart ✅ CBSE Suggested

python

# Program to display a scatter chart for given points

import matplotlib.pyplot as plt

x = [2, 9, 8, 5, 6]
y = [5, 10, 3, 7, 18]

plt.scatter(x, y, color='red', s=100)
plt.title("Scatter Chart")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.grid(True)
plt.show()

Expected Output: Five red dots plotted at coordinates (2,5), (9,10), (8,3), (5,7), (6,18).

Line chart vs scatter chart:

Line ChartScatter Chart
Points are connected by a linePoints are plotted individually, no line
Used for trends over time or sequenceUsed to find relationship between two variables
Example: Temperature change across monthsExample: Study hours vs exam marks

Program 6: Display a Bar Chart

python

# Program to display a bar chart showing subject-wise marks

import matplotlib.pyplot as plt

subjects = ["Math", "Science", "English", "AI", "Hindi"]
marks    = [85, 90, 72, 95, 78]

plt.bar(subjects, marks, color='green', width=0.5)
plt.title("Subject-wise Marks")
plt.xlabel("Subjects")
plt.ylabel("Marks")
plt.ylim(0, 100)
plt.show()

Expected Output: Five green vertical bars, one for each subject, with height matching the marks.

plt.ylim(0, 100) sets the Y-axis range from 0 to 100, which makes the bar heights easy to compare.


Program 7: Display a Histogram

python

# Program to display a histogram of student marks

import matplotlib.pyplot as plt

marks = [45, 52, 60, 63, 67, 70, 72, 74, 74, 78,
         80, 82, 85, 85, 88, 90, 91, 93, 95, 98]

plt.hist(marks, bins=5, color='orange', edgecolor='black')
plt.title("Distribution of Marks")
plt.xlabel("Marks Range")
plt.ylabel("Number of Students")
plt.show()

Expected Output: An orange bar chart showing how many students fall in each marks range (e.g., 45–57, 58–70, 71–83, 84–91, 92–98).

Histogram vs Bar chart:

  • A bar chart compares separate categories (subjects, names)
  • A histogram shows the distribution of one continuous variable (marks, height, age) by grouping values into ranges called bins

Section 3 — Pandas & CSV Programs (Programs 8–11)


Program 8: Read CSV File and Display 10 Rows ✅ CBSE Suggested

python

# Program to read a CSV file saved in your system and display 10 rows

import pandas as pd

df = pd.read_csv("data.csv")

print("First 10 rows of the dataset:")
print(df.head(10))

Expected Output: The first 10 rows of your CSV file displayed as a table with column headers.

Before running: Save a CSV file named data.csv in the same folder as your Jupyter Notebook. You can use any dataset — student marks, weather data, or download one from the CBSE suggested link in your textbook.

df.head(n) returns the first n rows. Default is 5 if you write df.head() without a number.


Program 9: Read CSV File and Display Its Information ✅ CBSE Suggested

python

# Program to read a CSV file and display its information

import pandas as pd

df = pd.read_csv("data.csv")

print("Shape of dataset (rows, columns):")
print(df.shape)

print("\nColumn names:")
print(df.columns.tolist())

print("\nDataset Information:")
print(df.info())

print("\nStatistical Summary:")
print(df.describe())

Expected Output (example for a marks dataset):

Shape of dataset (rows, columns):
(50, 4)

Column names:
['Name', 'Math', 'Science', 'AI']

Dataset Information:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 50 entries, 0 to 49
Data columns (total 4 columns): ...

Statistical Summary:
        Math    Science          AI
count  50.000   50.000      50.000
mean   74.200   71.800      80.400
...

What each method tells you:

MethodWhat It Shows
df.shapeNumber of rows and columns
df.columnsNames of all columns
df.info()Data types, non-null counts — reveals missing values
df.describe()Min, max, mean, std for all numeric columns

Program 10: Check and Handle Missing Values in a CSV

python

# Program to check for missing values and fill them

import pandas as pd

df = pd.read_csv("data.csv")

print("Missing values in each column:")
print(df.isnull().sum())

# Fill missing numeric values with the column mean
df.fillna(df.mean(numeric_only=True), inplace=True)

print("\nMissing values after filling:")
print(df.isnull().sum())

Expected Output:

Missing values in each column:
Name       0
Math       3
Science    1
AI         0
dtype: int64

Missing values after filling:
Name       0
Math       0
Science    0
AI         0
dtype: int64

Why this matters: Real-world datasets almost always have missing values — sensor failures, incomplete forms, data entry errors. Handling missing values is Step 1 of every AI project. fillna() replaces them; dropna() removes rows that have them.


Program 11: Filter Rows from a DataFrame

python

# Program to filter rows from a DataFrame based on a condition

import pandas as pd

data = {
    "Name"   : ["Arjun", "Priya", "Kiran", "Meena", "Rohan"],
    "Marks"  : [85, 72, 91, 68, 78],
    "Grade"  : ["B", "C", "A", "D", "C"]
}

df = pd.DataFrame(data)

# Filter: show only students who scored more than 75
high_scorers = df[df["Marks"] > 75]

print("Students scoring above 75:")
print(high_scorers)

Expected Output:

Students scoring above 75:
    Name  Marks Grade
0  Arjun     85     B
2  Kiran     91     A
4  Rohan     78     C

The condition df["Marks"] > 75 creates a True/False mask for each row. Putting it inside df[...] keeps only the rows where the condition is True. This is called boolean indexing — one of the most used operations in data analysis.


Section 4 — OpenCV Programs (Programs 12–15)

Before running OpenCV programs: You need an image file saved in the same folder as your notebook. Name it photo.jpg or change the filename in the code to match your file.


Program 12: Read an Image and Display It ✅ CBSE Suggested

python

# Program to read an image and display it using Python

import cv2

img = cv2.imread("photo.jpg")
cv2.imshow("My Image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Expected Output: A window opens showing your image.

How it works:

  • cv2.imread("photo.jpg") — loads the image from disk into memory as a NumPy array
  • cv2.imshow("My Image", img) — displays the image in a new window
  • cv2.waitKey(0) — waits until you press any key before continuing
  • cv2.destroyAllWindows() — closes the image window cleanly

Program 13: Read an Image and Identify Its Shape ✅ CBSE Suggested

python

# Program to read an image and identify its shape using Python

import cv2

img = cv2.imread("photo.jpg")

print("Image shape:", img.shape)
print("Height     :", img.shape[0], "pixels")
print("Width      :", img.shape[1], "pixels")
print("Channels   :", img.shape[2], "(3 = colour image: BGR)")

Expected Output (example):

Image shape: (480, 640, 3)
Height     : 480 pixels
Width      : 640 pixels
Channels   : 3 (3 = colour image: BGR)

What the shape means:

  • img.shape returns a tuple (height, width, channels)
  • Channels = 3 means the image is in colour (Blue, Green, Red — OpenCV uses BGR order, not RGB)
  • Channels = 1 would mean grayscale

Program 14: Convert a Colour Image to Grayscale

python

# Program to convert a colour image to grayscale

import cv2

img      = cv2.imread("photo.jpg")
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

print("Original image shape:", img.shape)
print("Grayscale image shape:", gray_img.shape)

cv2.imshow("Original",  img)
cv2.imshow("Grayscale", gray_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Expected Output:

Original image shape : (480, 640, 3)
Grayscale image shape: (480, 640)

Two windows open — one colour, one grayscale.

Why AI uses grayscale: Converting to grayscale reduces data from 3 channels to 1, making image processing faster. Many computer vision models, especially early CNNs, work on grayscale images to reduce computation.


Program 15: Resize an Image

python

# Program to resize an image using Python

import cv2

img = cv2.imread("photo.jpg")

print("Original size:", img.shape)

# Resize to 300 x 200 pixels (width=300, height=200)
resized_img = cv2.resize(img, (300, 200))

print("Resized size:", resized_img.shape)

cv2.imshow("Original Image", img)
cv2.imshow("Resized Image",  resized_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Expected Output:

Original size: (480, 640, 3)
Resized size : (200, 300, 3)

Note: In cv2.resize(), you pass (width, height) — the opposite order from img.shape which gives (height, width). This trips up many students in practicals.

Why resizing matters in AI: When you train a computer vision model, all input images must be the same size. Before feeding images into a model, you always resize them to a standard dimension — typically 224×224 or 128×128 depending on the model architecture.


Quick Revision Box

FunctionLibraryWhat It Does
np.array()NumPyConverts a list to a NumPy array
np.mean()NumPyCalculates average of an array
np.median()NumPyFinds the middle value
plt.plot()MatplotlibDraws a line chart
plt.scatter()MatplotlibDraws a scatter chart
plt.bar()MatplotlibDraws a bar chart
plt.hist()MatplotlibDraws a histogram
pd.read_csv()PandasLoads a CSV file into a DataFrame
df.head(n)PandasShows first n rows
df.info()PandasShows column types and missing value counts
df.isnull().sum()PandasCounts missing values per column
cv2.imread()OpenCVReads an image from disk
cv2.imshow()OpenCVDisplays an image in a window
img.shapeOpenCV/NumPyReturns (height, width, channels)
cv2.cvtColor()OpenCVConverts between colour modes
cv2.resize()OpenCVResizes an image to given dimensions

Practice Questions

Q1 (2 marks): Write a Python program to display a line chart using Matplotlib for the points (2,5) and (9,10).

Model Answer:

python

# Program to display a line chart from (2,5) to (9,10)
import matplotlib.pyplot as plt
x = [2, 9]
y = [5, 10]
plt.plot(x, y)
plt.title("Line Chart")
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.show()

Q2 (MCQ): What does img.shape return for a colour image of height 480 pixels and width 640 pixels?

a) (640, 480, 3) b) (480, 640) c) (480, 640, 3) d) (3, 480, 640)

Answer: c) (480, 640, 3) — shape returns (height, width, channels). Colour images have 3 channels (BGR in OpenCV).


Frequently Asked Questions

Q1: Do I need to run all 15 programs or just the 8 CBSE suggested ones? The CBSE 2025-26 PDF (Subject Code 417, Unit 7) lists 8 suggested programs. Your school may ask for all 8, or a selection. The 7 additional programs in this post (bar chart, histogram, missing values, filtering, grayscale, resize) are commonly tested by schools and build directly on the same libraries. Include as many as your teacher directs — having all 15 ready means you are covered either way.

Q2: I get an error when running OpenCV programs. What do I do? The most common errors: (1) the image file is not in the same folder as your notebook — check the file path; (2) OpenCV is not installed — run pip install opencv-python in your terminal or Anaconda prompt; (3) the image filename in your code does not match the actual file — Python is case-sensitive, so Photo.jpg and photo.jpg are different files. For a full list of common Python errors and fixes, see our Top 10 Python Errors & How to Fix Them guide.

Q3: What CSV file should I use for the Pandas programs? You can use any CSV. Good options: download the Palmer Penguins dataset (mentioned in the CBSE Class 10 sample projects), any dataset from Kaggle, or simply create your own with student names and marks in Excel and save as CSV. The programs work on any properly formatted CSV file.