CBSE Class 9 AI Practical File 2026-27 | 15 Python Programs with Output | Code 417
Class 9 AI Practical File
2026–27
All Python programs with code & output for your CBSE/KVS Class 9 AI practical file. Prepared as per Code 417 syllabus.
📥 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 — FreeWhy Your Class 9 AI Practical File Matters More Than You Think
For CBSE Class 9 students under Subject Code 417, the practical file isn't just paperwork your school asks for — it's where the AI syllabus actually clicks into place. Reading about "types of AI" in a textbook is one thing; watching a program you typed yourself sort a list, recognize a pattern, or print a result is what makes the concept stick during your board exam viva.
This file is built around the units your KVS/CBSE syllabus actually tests: Introduction to AI, the AI project cycle and ethics, basic Python building blocks, and simple data-handling programs. Each program maps directly to a learning outcome your teacher will check off — not random code dumped together.
How to Actually Use This File (Not Just Submit It)
Most students copy the code, run it once, and move on. That's the fastest way to forget everything by exam time. Instead:
- Type the code yourself instead of copy-pasting — your fingers remembering syntax is half the battle in a practical exam where you can't paste anything.
- Change one variable and predict the output before running it. If you can predict it correctly, you actually understand the program — not just memorized it.
- Read the "aim" line out loud before each program. Examiners often ask "what was the aim of this program?" in the viva, and it's an easy mark to lose if you've never said it aloud.
Common Mistakes Students Make
- Confusing Artificial Intelligence, Machine Learning, and Deep Learning as the same thing — they're nested, not identical (AI is the umbrella, ML is a method inside it, DL is a method inside ML).
- Forgetting that the AI Project Cycle has a fixed order (Problem Scoping → Data Acquisition → Data Exploration → Modelling → Evaluation) — board exams love asking you to sequence this correctly.
- Writing Python with incorrect indentation — Python uses indentation as syntax, not just style, so a misplaced space can change what your code actually does.
Class IX | Subject: Artificial Intelligence | Code: 417 | Academic Year 2026-27
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
🛠️ 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
pip install numpy matplotlib in command prompt before running programs.
# 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!")
============================================= 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!
# 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")
--- 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
# 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.")
Student: Aryan Marks : [85, 92, 78, 95, 88] Total : 438 Average: 87.6 Highest: 95 Lowest : 78 Aryan has PASSED! 🎉
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")
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
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!")
[Colourful bar chart window opens showing marks for each student] [Red dashed line shows pass mark at 33] Bar chart displayed successfully!
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!")
[Line graph window opens with temperature data points connected] [Red shaded area shown under the line] Line graph displayed successfully!
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.")
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.
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")
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
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!")
[White canvas with Blue rectangle, Green circle, Red line, Purple ellipse, and text label] Shapes drawn successfully!
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}")
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
# 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)")
Word Frequency Analysis: ------------------------------ Word Count ------------------------------ ai 3 ███ is 2 ██ great 1 █ Most frequent: 'ai' (3 times)
# 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
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! 👋
# 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}")
Pattern 1: Number Triangle
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Pattern 2: Star Pyramid
*
* *
* * *
* * * *
* * * * *
# 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)
How many terms? 10 First 10 Fibonacci numbers: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
# 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
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
Comments
Post a Comment