CBSE Class 9 AI Practical File 2026-27 | 15 Python Programs with Output | Code 417
📗 AI Logic School
Class 9 AI Practical File
2025–26
All Python programs with code & output for your CBSE/KVS Class 9 AI practical file. Prepared as per Code 417 syllabus.
15+
Programs
5
Units
100%
CBSE
Free
Download
📥 Download Complete Class 9 AI Practical File PDF
All 15 programs with aim, code, output and viva questions in one printable PDF. Free for CBSE students.
⬇️ Download Full PDF — Free
ℹ️
Class IX | Subject: Artificial Intelligence | Code: 417 | Academic Year 2025-26
All programs are written in Python 3 and tested as per the latest CBSE Class 9 AI syllabus. Each program includes aim, code, and expected output.
📚 Syllabus Units Covered
Unit 1
Introduction to AI
AI concepts, types of AI, applications in daily life, AI project cycle.
2 Programs
Unit 2
Data Science
Python basics, variables, lists, NumPy arrays, data handling.
4 Programs
Unit 3
Computer Vision
Image basics, pixel manipulation, OpenCV introduction.
3 Programs
Unit 4
Natural Language Processing
Text processing, tokenisation, basic NLP with Python.
3 Programs
Unit 5
Logical Reasoning
Problem solving, algorithms, flowcharts, Python logic programs.
3 Programs
🛠️ How to Use This Practical File
- 1️⃣Read the Aim — Understand the purpose of each program before coding.
- 2️⃣Copy the Code — Click the Copy button and paste in IDLE or VS Code.
- 3️⃣Run & Check — Run the program and match your output with the expected output.
- 4️⃣Write in File — Note Aim, Code, and Output neatly in your practical file.
- 5️⃣Download PDF — Download the complete practical file PDF using the button below.
💻 Python Programs with Code & Output
📌 Note: Make sure Python 3 is installed on your computer. Install required libraries using
pip install numpy matplotlib in command prompt before running programs.
Prog 01
Introduction to Python — Print & Input
Unit 1
🎯 Aim
To write a basic Python program to display information about Artificial Intelligence and accept user input.
🟢 Python Code
# Program 1: Introduction to AI
print("=" * 45)
print(" Welcome to Artificial Intelligence!")
print("=" * 45)
print("AI stands for Artificial Intelligence.")
print("It makes computers think like humans.")
print()
name = input("Enter your name: ")
grade = input("Enter your class: ")
print()
print(f"Hello {name} from Class {grade}!")
print("Let's explore the world of AI together!")
🖥️ Expected Output
============================================= Welcome to Artificial Intelligence! ============================================= AI stands for Artificial Intelligence. It makes computers think like humans. Enter your name: Riya Enter your class: 9 Hello Riya from Class 9! Let's explore the world of AI together!
Prog 02
AI Application Quiz Program
Unit 1
🎯 Aim
To create a simple quiz program about AI applications using Python if-else conditions.
🟢 Python Code
# Program 2: AI Quiz
score = 0
print("--- AI Applications Quiz ---")
print()
q1 = input("Q1. Which AI app gives movie suggestions? ")
if q1.lower() in ["netflix", "recommendation system"]:
print("Correct! ✓"); score += 1
else:
print("Answer: Netflix (Recommendation System)")
q2 = input("Q2. Which AI technology reads your face? ")
if q2.lower() in ["face recognition", "facial recognition"]:
print("Correct! ✓"); score += 1
else:
print("Answer: Face Recognition")
q3 = input("Q3. Name one AI voice assistant: ")
if q3.lower() in ["siri", "alexa", "google assistant", "cortana"]:
print("Correct! ✓"); score += 1
else:
print("Answer: Siri / Alexa / Google Assistant")
print()
print(f"Your Score: {score}/3")
🖥️ Expected Output
--- AI Applications Quiz --- Q1. Which AI app gives movie suggestions? Netflix Correct! ✓ Q2. Which AI technology reads your face? Face Recognition Correct! ✓ Q3. Name one AI voice assistant: Alexa Correct! ✓ Your Score: 3/3
Prog 03
Python Variables, List & Basic Operations
Unit 2
🎯 Aim
To demonstrate use of variables, lists, and basic arithmetic operations in Python for data handling.
🟢 Python Code
# Program 3: Variables and Lists
student_name = "Aryan"
marks = [85, 92, 78, 95, 88]
print(f"Student: {student_name}")
print(f"Marks : {marks}")
print()
print(f"Total : {sum(marks)}")
print(f"Average: {sum(marks)/len(marks):.1f}")
print(f"Highest: {max(marks)}")
print(f"Lowest : {min(marks)}")
print()
avg = sum(marks) / len(marks)
if avg >= 33:
print(f"{student_name} has PASSED! 🎉")
else:
print(f"{student_name} needs to work harder.")
🖥️ Expected Output
Student: Aryan Marks : [85, 92, 78, 95, 88] Total : 438 Average: 87.6 Highest: 95 Lowest : 78 Aryan has PASSED! 🎉
Prog 04
NumPy Array — Create & Operations
Unit 2
🎯 Aim
To create NumPy arrays and perform basic mathematical operations used in Data Science.
🟢 Python Code
import numpy as np
temps_week = np.array([32, 35, 30, 28, 33, 36, 31])
days = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]
print("Weekly Temperature Data:")
for day, temp in zip(days, temps_week):
print(f" {day}: {temp}°C")
print()
print(f"Average Temperature: {np.mean(temps_week):.1f}°C")
print(f"Hottest Day : {days[np.argmax(temps_week)]} ({np.max(temps_week)}°C)")
print(f"Coolest Day : {days[np.argmin(temps_week)]} ({np.min(temps_week)}°C)")
print(f"Temperature Range : {np.max(temps_week) - np.min(temps_week)}°C")
🖥️ Expected Output
Weekly Temperature Data: Mon: 32°C Tue: 35°C Wed: 30°C Thu: 28°C Fri: 33°C Sat: 36°C Sun: 31°C Average Temperature: 32.1°C Hottest Day : Sat (36°C) Coolest Day : Thu (28°C) Temperature Range : 8°C
Prog 05
Bar Chart using Matplotlib
Unit 2
🎯 Aim
To create a bar chart showing student marks using the Matplotlib library in Python.
🟢 Python Code
import matplotlib.pyplot as plt
students = ['Aarav','Priya','Rohan','Meena','Karan','Sita']
marks = [85, 92, 78, 96, 88, 74]
colors = ['#3498db','#2ecc71','#e74c3c','#9b59b6','#f39c12','#1abc9c']
plt.figure(figsize=(9, 5))
bars = plt.bar(students, marks, color=colors, edgecolor='white', linewidth=1.2)
for bar, mark in zip(bars, marks):
plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 1,
str(mark), ha='center', va='bottom', fontweight='bold')
plt.title('Class 9 Student Marks — Bar Chart', fontsize=14, fontweight='bold')
plt.xlabel('Student Name')
plt.ylabel('Marks (out of 100)')
plt.ylim(0, 110)
plt.axhline(y=33, color='red', linestyle='--', label='Pass Mark (33)')
plt.legend()
plt.tight_layout()
plt.show()
print("Bar chart displayed successfully!")
🖥️ Expected Output
[Colourful bar chart window opens showing marks for each student] [Red dashed line shows pass mark at 33] Bar chart displayed successfully!
Prog 06
Line Graph — Temperature over a Week
Unit 2
🎯 Aim
To plot a line graph showing temperature variation over a week using Matplotlib.
🟢 Python Code
import matplotlib.pyplot as plt
days = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
temps = [32, 35, 30, 28, 33, 36, 31]
plt.figure(figsize=(9, 5))
plt.plot(days, temps, marker='o', color='#e74c3c',
linewidth=2.5, markersize=8, markerfacecolor='white',
markeredgewidth=2, label='Temperature')
plt.fill_between(days, temps, alpha=0.15, color='#e74c3c')
for i, (day, temp) in enumerate(zip(days, temps)):
plt.annotate(f'{temp}°C', (day, temp),
textcoords="offset points", xytext=(0,10), ha='center')
plt.title('Weekly Temperature — Line Graph', fontsize=13, fontweight='bold')
plt.xlabel('Day of Week')
plt.ylabel('Temperature (°C)')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
print("Line graph displayed successfully!")
🖥️ Expected Output
[Line graph window opens with temperature data points connected] [Red shaded area shown under the line] Line graph displayed successfully!
Prog 07
Read & Display an Image using OpenCV
Unit 3
🎯 Aim
To read an image from the computer and display it using the OpenCV library in Python.
🟢 Python Code
import cv2
img = cv2.imread('photo.jpg')
print("Image Details:")
print(f" Height : {img.shape[0]} pixels")
print(f" Width : {img.shape[1]} pixels")
print(f" Channels: {img.shape[2]} (BGR)")
print(f" Size : {img.size} total pixels")
cv2.imshow('My Image', img)
print("\nPress any key to close the image window...")
cv2.waitKey(0)
cv2.destroyAllWindows()
print("Window closed.")
🖥️ Expected Output
Image Details: Height : 480 pixels Width : 640 pixels Channels: 3 (BGR) Size : 921600 total pixels Press any key to close the image window... [Image window opens displaying the photo] Window closed.
Prog 08
Convert Image to Grayscale
Unit 3
🎯 Aim
To convert a colour image into grayscale using OpenCV and compare both images.
🟢 Python Code
import cv2
color_img = cv2.imread('photo.jpg')
gray_img = cv2.cvtColor(color_img, cv2.COLOR_BGR2GRAY)
print(f"Original image shape : {color_img.shape}")
print(f"Grayscale image shape: {gray_img.shape}")
print()
print("Colour image has 3 channels (Blue, Green, Red)")
print("Grayscale has only 1 channel (intensity)")
cv2.imshow('Original — Colour', color_img)
cv2.imshow('Converted — Grayscale', gray_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite('gray_photo.jpg', gray_img)
print("Grayscale image saved as gray_photo.jpg")
🖥️ Expected Output
Original image shape : (480, 640, 3) Grayscale image shape: (480, 640) Colour image has 3 channels (Blue, Green, Red) Grayscale has only 1 channel (intensity) [Two windows open: original colour + grayscale] Grayscale image saved as gray_photo.jpg
Prog 09
Draw Shapes on Image using OpenCV
Unit 3
🎯 Aim
To draw basic shapes (rectangle, circle, line, text) on an image using OpenCV drawing functions.
🟢 Python Code
import cv2
import numpy as np
canvas = np.ones((400, 600, 3), dtype=np.uint8) * 255
cv2.rectangle(canvas, (50, 50), (200, 150), (255, 0, 0), 3)
cv2.circle(canvas, (350, 100), 80, (0, 255, 0), 3)
cv2.line(canvas, (50, 200), (550, 200), (0, 0, 255), 2)
cv2.ellipse(canvas, (300, 300), (120, 60), 0, 0, 360, (128,0,128), 3)
cv2.putText(canvas, 'Class 9 AI — OpenCV Shapes',
(60, 370), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,0), 2)
cv2.imshow('OpenCV Drawing', canvas)
cv2.waitKey(0)
cv2.destroyAllWindows()
print("Shapes drawn successfully!")
🖥️ Expected Output
[White canvas with Blue rectangle, Green circle, Red line, Purple ellipse, and text label] Shapes drawn successfully!
Prog 10
Text Tokenisation using NLTK
Unit 4
🎯 Aim
To split a paragraph into words and sentences using NLTK tokenisation in Python.
🟢 Python Code
import nltk
nltk.download('punkt', quiet=True)
from nltk.tokenize import word_tokenize, sent_tokenize
text = ("AI is changing the world. "
"Machines can now see, hear and speak. "
"Python is used to build AI programs.")
print("Original Text:")
print(text)
print()
sentences = sent_tokenize(text)
print(f"Number of Sentences: {len(sentences)}")
for i, s in enumerate(sentences, 1):
print(f" {i}. {s}")
words = word_tokenize(text)
print()
print(f"Number of Words: {len(words)}")
print(f"Words: {words}")
🖥️ Expected Output
Number of Sentences: 3 1. AI is changing the world. 2. Machines can now see, hear and speak. 3. Python is used to build AI programs. Number of Words: 23
Prog 11
Count Word Frequency in a Text
Unit 4
🎯 Aim
To count the frequency of each word in a given sentence using Python dictionary.
🟢 Python Code
# Program 11: Word Frequency Counter
text = "AI is great AI helps humans AI is the future of technology"
words = text.lower().split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
sorted_freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
print("Word Frequency Analysis:")
print("-" * 30)
print(f"{'Word':<15} {'Count':>5}")
print("-" * 30)
for word, count in sorted_freq:
bar = "█" * count
print(f"{word:<15} {count:>5} {bar}")
print()
print(f"Total unique words: {len(freq)}")
print(f"Most frequent: '{sorted_freq[0][0]}' ({sorted_freq[0][1]} times)")
🖥️ Expected Output
Word Frequency Analysis: ------------------------------ Word Count ------------------------------ ai 3 ███ is 2 ██ great 1 █ Most frequent: 'ai' (3 times)
Prog 12
Simple Chatbot using if-else
Unit 4
🎯 Aim
To create a simple rule-based chatbot for Class 9 students using Python if-else statements.
🟢 Python Code
# Program 12: Simple Chatbot
def chatbot(msg):
msg = msg.lower()
if any(w in msg for w in ["hello","hi","hey"]):
return "Hello! I am Class 9 AI Bot! How can I help?"
elif "name" in msg:
return "I am EduBot — your Class 9 AI assistant!"
elif "ai" in msg:
return "AI stands for Artificial Intelligence!"
elif "python" in msg:
return "Python is a programming language used in AI."
elif "bye" in msg or "exit" in msg:
return "Goodbye! Keep learning! 👋"
else:
return "I did not understand. Ask me about AI or Python!"
print("EduBot Started! (Type 'bye' to exit)")
print("-" * 40)
while True:
user = input("You : ")
resp = chatbot(user)
print(f"Bot : {resp}")
if "bye" in user.lower():
break
🖥️ Expected Output
EduBot Started! (Type 'bye' to exit) ---------------------------------------- You : hello Bot : Hello! I am Class 9 AI Bot! How can I help? You : what is ai Bot : AI stands for Artificial Intelligence! You : bye Bot : Goodbye! Keep learning! 👋
Prog 13
Number Pattern using Loops
Unit 5
🎯 Aim
To demonstrate logical reasoning using Python loops to print number patterns.
🟢 Python Code
# Program 13: Number Patterns
print("Pattern 1: Number Triangle")
for i in range(1, 6):
print(" ".join(str(j) for j in range(1, i+1)))
print()
print("Pattern 2: Star Pyramid")
for i in range(1, 6):
print(" " * (5-i) + "* " * i)
print()
print("Pattern 3: Multiplication Table of 5")
for i in range(1, 11):
print(f" 5 x {i:2d} = {5*i:3d}")
🖥️ Expected Output
Pattern 1: Number Triangle
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Pattern 2: Star Pyramid
*
* *
* * *
* * * *
* * * * *
Prog 14
Fibonacci Sequence — AI Pattern Recognition
Unit 5
🎯 Aim
To generate and display the Fibonacci sequence using Python, demonstrating pattern recognition used in AI.
🟢 Python Code
# Program 14: Fibonacci Sequence
print("Fibonacci Sequence in AI")
print("Used in pattern recognition and nature!")
print()
n = int(input("How many terms? "))
a, b = 0, 1
fib_list = []
for _ in range(n):
fib_list.append(a)
a, b = b, a + b
print(f"\nFirst {n} Fibonacci numbers:")
print(fib_list)
print()
print("Visualisation:")
for num in fib_list[:10]:
print("█" * (num % 20 + 1), num)
🖥️ Expected Output
How many terms? 10 First 10 Fibonacci numbers: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Prog 15
Simple Calculator — AI Decision Making
Unit 5
🎯 Aim
To create a simple calculator using Python functions, demonstrating AI decision-making using conditions.
🟢 Python Code
# Program 15: Smart Calculator
def calculate(a, op, b):
if op == '+': return a + b
elif op == '-': return a - b
elif op == '*': return a * b
elif op == '/':
if b == 0: return "Error: Cannot divide by zero!"
return a / b
else: return "Unknown operator!"
print("Smart AI Calculator")
print("Operations: + - * /")
print("-" * 30)
while True:
try:
num1 = float(input("Enter first number : "))
op = input("Enter operator (+,-,*,/) : ")
num2 = float(input("Enter second number: "))
result = calculate(num1, op, num2)
print(f"Result: {num1} {op} {num2} = {result}")
except ValueError:
print("Please enter valid numbers!")
again = input("Calculate again? (yes/no): ")
if again.lower() != 'yes':
print("Goodbye! 👋")
break
🖥️ Expected Output
Smart AI Calculator Enter first number : 25 Enter operator : * Enter second number: 4 Result: 25.0 * 4.0 = 100.0 Goodbye! 👋
📥 Download Complete Class 9 AI Practical File PDF
All 15 programs with aim, code, output and viva questions in one printable PDF. Perfect for CBSE practical file submission.
⬇️ Download Full PDF — Free
📌 Note: This page shows all 15 programs. Download the PDF above for a printable version ready for your practical file submission.
❓ Important Viva Questions
Q1. What is Artificial Intelligence?
AI is the ability of a machine to think, learn and solve problems like a human being.
Q2. Name 3 applications of AI in daily life.
Google Maps, Face Unlock, Voice Assistants (Alexa/Siri), Netflix recommendations, Spam filters.
Q3. What is Python? Why is it used in AI?
Python is a simple programming language. It is used in AI because it has many ready-made libraries like NumPy, Matplotlib, and OpenCV.
Q4. What is NumPy?
NumPy is a Python library used to create and work with arrays and perform mathematical operations on data.
Q5. What is Matplotlib?
Matplotlib is a Python library used to create charts and graphs like bar charts, pie charts, and line graphs.
Q6. What is Computer Vision?
Computer Vision is a field of AI that enables computers to understand and interpret images and videos.
Q7. What is OpenCV?
OpenCV is a Python library used for image processing, face detection, and video analysis.
Q8. What is NLP?
NLP stands for Natural Language Processing — it enables computers to understand and generate human language.
Q9. What is tokenisation?
Tokenisation is splitting a sentence into individual words or sentences using NLTK library.
Q10. What is a chatbot?
A chatbot is an AI program that simulates human conversation using rules or machine learning.
🔗 More Resources on AI Logic School
📘 Class 12
Class XII AI Lab Manual
Complete Python programs for CBSE Class 12 AI subject 2025-26.
📗 Class 10
Class 10 AI Practical File
15 Python programs for CBSE Class 10 AI Code 417.
📙 Worksheets
CBSE AI Worksheets
Free printable worksheets for Classes 6 to 12 AI subject.
Comments
Post a Comment