COMPUTER SCIENCE / INFORMATICS PRACTICES
PRACTICAL FILE
Python Programs & MySQL Connectivity
Student's Name: [Student's Name]
Class & Section: XII - [Section]
Roll Number: [Roll No.]
Subject: Computer Science
School Name: [School Name]
Session: 2026-27
INDEX
[Link]. Program Title Page
No.
1 Program to check whether a number is prime or not.
2 Program to find the factorial of a number using recursion.
3 Program to generate the Fibonacci series up to n terms.
4 Program to check whether a given string is a palindrome.
5 Program to check whether a number is an Armstrong number.
6 Program to count the number of vowels and consonants in a
string.
7 Program to count the frequency of each word in a string.
8 Program to find the largest and smallest number in a list.
9 Program to remove duplicate elements from a list.
10 Program to sort a list of numbers using Bubble Sort.
11 Program to search an element in a list using Binary Search.
12 Program to implement a Stack using a list (PUSH and POP
operations).
13 Program to implement a Queue using a list (menu-driven).
14 Program to demonstrate functions with default and keyword
arguments.
15 Program to read a text file and count the number of lines, words,
and characters.
16 Program to copy the contents of one text file into another file.
17 Program to remove all lines containing a given word from a text
file.
18 Program to create a binary file to store and search student
records using pickle.
19 Program to update a record in a binary file.
20 Program to demonstrate CSV file handling (writing and reading
records).
21 Program to connect Python with MySQL and create a database
and table.
22 Program to insert records into a MySQL table from Python.
23 Program to fetch and display records from a MySQL table.
24 Program to update a record in a MySQL table using Python.
25 Program to delete a record from a MySQL table using Python.
Page 2 of 29
Program – 1
Aim: To accept a number from the user and check whether it is a prime number.
Source Code:
num = int(input("Enter a number: "))
if num > 1:
for i in range(2, int(num**0.5)+1):
if num % i == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
Output:
Enter a number: 29
29 is a prime number
Page 3 of 29
Program – 2
Aim: To accept a number from the user and compute its factorial using a recursive
function.
Source Code:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
num = int(input("Enter a number: "))
print("Factorial of", num, "is", factorial(num))
Output:
Enter a number: 5
Factorial of 5 is 120
Page 4 of 29
Program – 3
Aim: To accept the number of terms from the user and print the Fibonacci series.
Source Code:
n = int(input("Enter number of terms: "))
a, b = 0, 1
print("Fibonacci Series:")
for i in range(n):
print(a, end=' ')
a, b = b, a + b
print()
Output:
Enter number of terms: 10
Fibonacci Series:
0 1 1 2 3 5 8 13 21 34
Page 5 of 29
Program – 4
Aim: To accept a string from the user and check whether it reads the same
backwards.
Source Code:
s = input("Enter a string: ")
if s == s[::-1]:
print(s, "is a palindrome")
else:
print(s, "is not a palindrome")
Output:
Enter a string: madam
madam is a palindrome
Page 6 of 29
Program – 5
Aim: To accept a number from the user and check whether it is an Armstrong
number.
Source Code:
num = int(input("Enter a number: "))
order = len(str(num))
total = 0
temp = num
while temp > 0:
digit = temp % 10
total += digit ** order
temp //= 10
if num == total:
print(num, "is an Armstrong number")
else:
print(num, "is not an Armstrong number")
Output:
Enter a number: 153
153 is an Armstrong number
Page 7 of 29
Program – 6
Aim: To accept a string from the user and count the vowels and consonants present in
it.
Source Code:
s = input("Enter a string: ")
vowels = 0
consonants = 0
for ch in s:
if [Link]():
if [Link]() in 'aeiou':
vowels += 1
else:
consonants += 1
print("Number of vowels:", vowels)
print("Number of consonants:", consonants)
Output:
Enter a string: Computer Science
Number of vowels: 6
Number of consonants: 9
Page 8 of 29
Program – 7
Aim: To accept a string from the user and display the frequency of each word.
Source Code:
s = input("Enter a string: ")
words = [Link]()
freq = {}
for w in words:
freq[w] = [Link](w, 0) + 1
print("Word Frequency:")
for w in freq:
print(w, ":", freq[w])
Output:
Enter a string: the quick brown fox jumps over the lazy fox
Word Frequency:
the : 2
quick : 1
brown : 1
fox : 2
jumps : 1
over : 1
lazy : 1
Page 9 of 29
Program – 8
Aim: To find and display the largest and smallest elements of a given list.
Source Code:
lst = [12, 45, 2, 41, 31, 10, 8, 6, 4]
print("List:", lst)
print("Largest element:", max(lst))
print("Smallest element:", min(lst))
Output:
List: [12, 45, 2, 41, 31, 10, 8, 6, 4]
Largest element: 45
Smallest element: 2
Page 10 of 29
Program – 9
Aim: To remove duplicate elements from a given list and display the resulting list.
Source Code:
lst = [10, 20, 10, 30, 20, 40, 50, 40]
print("Original list:", lst)
result = []
for item in lst:
if item not in result:
[Link](item)
print("List after removing duplicates:", result)
Output:
Original list: [10, 20, 10, 30, 20, 40, 50, 40]
List after removing duplicates: [10, 20, 30, 40, 50]
Page 11 of 29
Program – 10
Aim: To sort a given list of numbers in ascending order using the Bubble Sort
technique.
Source Code:
lst = [64, 34, 25, 12, 22, 11, 90]
print("Original list:", lst)
n = len(lst)
for i in range(n - 1):
for j in range(n - i - 1):
if lst[j] > lst[j + 1]:
lst[j], lst[j + 1] = lst[j + 1], lst[j]
print("Sorted list:", lst)
Output:
Original list: [64, 34, 25, 12, 22, 11, 90]
Sorted list: [11, 12, 22, 25, 34, 64, 90]
Page 12 of 29
Program – 11
Aim: To search for an element in a sorted list using the Binary Search technique.
Source Code:
lst = [11, 22, 25, 34, 64, 90]
print("List:", lst)
key = int(input("Enter the element to search: "))
low, high = 0, len(lst) - 1
found = False
while low <= high:
mid = (low + high) // 2
if lst[mid] == key:
found = True
print("Element found at index", mid)
break
elif lst[mid] < key:
low = mid + 1
else:
high = mid - 1
if not found:
print("Element not found in the list")
Output:
List: [11, 22, 25, 34, 64, 90]
Enter the element to search: 34
Element found at index 3
Page 13 of 29
Program – 12
Aim: To implement Stack operations (PUSH, POP, DISPLAY) using a menu-driven
program.
Source Code:
stack = []
while True:
print("\n1. PUSH 2. POP 3. DISPLAY 4. EXIT")
ch = int(input("Enter your choice: "))
if ch == 1:
val = input("Enter value to push: ")
[Link](val)
elif ch == 2:
if stack == []:
print("Stack is empty")
else:
print("Popped element:", [Link]())
elif ch == 3:
print("Stack:", stack)
elif ch == 4:
break
else:
print("Invalid choice")
Output:
1. PUSH 2. POP 3. DISPLAY 4. EXIT
Enter your choice: 1
Enter value to push: 10
1. PUSH 2. POP 3. DISPLAY 4. EXIT
Enter your choice: 1
Enter value to push: 20
1. PUSH 2. POP 3. DISPLAY 4. EXIT
Enter your choice: 1
Enter value to push: 30
1. PUSH 2. POP 3. DISPLAY 4. EXIT
Enter your choice: 3
Stack: ['10', '20', '30']
1. PUSH 2. POP 3. DISPLAY 4. EXIT
Enter your choice: 2
Popped element: 30
Page 14 of 29
1. PUSH 2. POP 3. DISPLAY 4. EXIT
Enter your choice: 3
Stack: ['10', '20']
1. PUSH 2. POP 3. DISPLAY 4. EXIT
Enter your choice: 4
Page 15 of 29
Program – 13
Aim: To implement Queue operations (INSERT, DELETE, DISPLAY) using a
menu-driven program.
Source Code:
queue = []
while True:
print("\n1. INSERT 2. DELETE 3. DISPLAY 4. EXIT")
ch = int(input("Enter your choice: "))
if ch == 1:
val = input("Enter value to insert: ")
[Link](val)
elif ch == 2:
if queue == []:
print("Queue is empty")
else:
print("Deleted element:", [Link](0))
elif ch == 3:
print("Queue:", queue)
elif ch == 4:
break
else:
print("Invalid choice")
Output:
1. INSERT 2. DELETE 3. DISPLAY 4. EXIT
Enter your choice: 1
Enter value to insert: A
1. INSERT 2. DELETE 3. DISPLAY 4. EXIT
Enter your choice: 1
Enter value to insert: B
1. INSERT 2. DELETE 3. DISPLAY 4. EXIT
Enter your choice: 1
Enter value to insert: C
1. INSERT 2. DELETE 3. DISPLAY 4. EXIT
Enter your choice: 3
Queue: ['A', 'B', 'C']
1. INSERT 2. DELETE 3. DISPLAY 4. EXIT
Enter your choice: 2
Deleted element: A
Page 16 of 29
1. INSERT 2. DELETE 3. DISPLAY 4. EXIT
Enter your choice: 3
Queue: ['B', 'C']
1. INSERT 2. DELETE 3. DISPLAY 4. EXIT
Enter your choice: 4
Page 17 of 29
Program – 14
Aim: To demonstrate the use of default arguments and keyword arguments in a user-
defined function.
Source Code:
def student_info(name, age=18, course="Computer Science"):
print("Name:", name)
print("Age:", age)
print("Course:", course)
print()
student_info("Aarav")
student_info("Diya", 17)
student_info(name="Kabir", course="Informatics Practices",
age=16)
Output:
Name: Aarav
Age: 18
Course: Computer Science
Name: Diya
Age: 17
Course: Computer Science
Name: Kabir
Age: 16
Course: Informatics Practices
Page 18 of 29
Program – 15
Aim: To read a text file and count the total number of lines, words, and characters
present in it.
Source Code:
with open("[Link]", "w") as f:
[Link]("Python is a versatile language.\n")
[Link]("It is widely used in AI and Data Science.\n")
[Link]("CBSE promotes Python for Computer Science.\n")
lines = words = chars = 0
with open("[Link]", "r") as f:
for line in f:
lines += 1
words += len([Link]())
chars += len(line)
print("Number of lines:", lines)
print("Number of words:", words)
print("Number of characters:", chars)
Output:
Number of lines: 3
Number of words: 20
Number of characters: 117
Page 19 of 29
Program – 16
Aim: To copy the contents of a source text file into a destination text file.
Source Code:
with open("[Link]", "w") as f:
[Link]("This is the content of the source file.\n")
[Link]("It will be copied to the destination file.\n")
with open("[Link]", "r") as src, open("[Link]",
"w") as dst:
for line in src:
[Link](line)
print("File copied successfully.")
print("\nContents of [Link]:")
with open("[Link]", "r") as f:
print([Link]())
Output:
File copied successfully.
Contents of [Link]:
This is the content of the source file.
It will be copied to the destination file.
Page 20 of 29
Program – 17
Aim: To read a text file and remove all the lines that contain a specific word.
Source Code:
with open("[Link]", "w") as f:
[Link]("Apple is a fruit.\n")
[Link]("Python is a programming language.\n")
[Link]("Mango is a fruit.\n")
[Link]("Java is a programming language.\n")
word = "fruit"
with open("[Link]", "r") as f:
lines = [Link]()
with open("[Link]", "w") as f:
for line in lines:
if word not in line:
[Link](line)
print("Lines containing '" + word + "' removed.")
print("\nRemaining content:")
with open("[Link]", "r") as f:
print([Link]())
Output:
Lines containing 'fruit' removed.
Remaining content:
Python is a programming language.
Java is a programming language.
Page 21 of 29
Program – 18
Aim: To create a binary file containing student records and search for a record using
the roll number.
Source Code:
import pickle
students = [
{"rollno": 1, "name": "Aarav", "marks": 89},
{"rollno": 2, "name": "Diya", "marks": 92},
{"rollno": 3, "name": "Kabir", "marks": 76}
]
with open("[Link]", "wb") as f:
[Link](students, f)
roll = int(input("Enter roll number to search: "))
with open("[Link]", "rb") as f:
data = [Link](f)
found = False
for rec in data:
if rec["rollno"] == roll:
print("Record found:", rec)
found = True
break
if not found:
print("Record not found")
Output:
Enter roll number to search: 2
Record found: {'rollno': 2, 'name': 'Diya', 'marks': 92}
Page 22 of 29
Program – 19
Aim: To read a binary file containing student records and update the marks of a given
roll number.
Source Code:
import pickle
students = [
{"rollno": 1, "name": "Aarav", "marks": 89},
{"rollno": 2, "name": "Diya", "marks": 92},
{"rollno": 3, "name": "Kabir", "marks": 76}
]
with open("[Link]", "wb") as f:
[Link](students, f)
with open("[Link]", "rb") as f:
data = [Link](f)
roll = int(input("Enter roll number to update: "))
new_marks = int(input("Enter new marks: "))
for rec in data:
if rec["rollno"] == roll:
rec["marks"] = new_marks
break
with open("[Link]", "wb") as f:
[Link](data, f)
print("Record updated successfully.")
with open("[Link]", "rb") as f:
updated = [Link](f)
print(updated)
Output:
Enter roll number to update: 2
Enter new marks: 95
Record updated successfully.
[{'rollno': 1, 'name': 'Aarav', 'marks': 89}, {'rollno': 2,
'name': 'Diya', 'marks': 95}, {'rollno': 3, 'name': 'Kabir',
'marks': 76}]
Page 23 of 29
Program – 20
Aim: To write student records into a CSV file and then read and display the contents
of the CSV file.
Source Code:
import csv
with open("[Link]", "w", newline="") as f:
writer = [Link](f)
[Link](["Name", "Subject", "Marks"])
[Link](["Aarav", "Computer Science", 89])
[Link](["Diya", "Computer Science", 92])
[Link](["Kabir", "Computer Science", 76])
print("Data written to [Link]\n")
print("Contents of [Link]:")
with open("[Link]", "r") as f:
reader = [Link](f)
for row in reader:
print(row)
Output:
Data written to [Link]
Contents of [Link]:
['Name', 'Subject', 'Marks']
['Aarav', 'Computer Science', '89']
['Diya', 'Computer Science', '92']
['Kabir', 'Computer Science', '76']
Page 24 of 29
Program – 21
Aim: To establish a connection between Python and MySQL, and create a database
and a table.
Source Code:
import [Link]
conn = [Link](host="localhost", user="root",
password="yourpassword")
cursor = [Link]()
[Link]("CREATE DATABASE IF NOT EXISTS school")
[Link]("USE school")
[Link]("""CREATE TABLE IF NOT EXISTS student (
rollno INT PRIMARY KEY,
name VARCHAR(30),
marks INT
)""")
print("Database and table created successfully.")
[Link]()
Output:
Database and table created successfully.
Page 25 of 29
Program – 22
Aim: To insert multiple student records into a MySQL table using Python.
Source Code:
import [Link]
conn = [Link](host="localhost", user="root",
password="yourpassword",
database="school")
cursor = [Link]()
data = [(1, "Aarav", 89), (2, "Diya", 92), (3, "Kabir", 76)]
[Link]("INSERT INTO student (rollno, name, marks)
VALUES (%s, %s, %s)", data)
[Link]()
print([Link], "records inserted successfully.")
[Link]()
Output:
3 records inserted successfully.
Page 26 of 29
Program – 23
Aim: To connect to a MySQL database and display all records stored in a table.
Source Code:
import [Link]
conn = [Link](host="localhost", user="root",
password="yourpassword",
database="school")
cursor = [Link]()
[Link]("SELECT * FROM student")
rows = [Link]()
print("Rollno\tName\tMarks")
for row in rows:
print(row[0], "\t", row[1], "\t", row[2])
[Link]()
Output:
Rollno Name Marks
1 Aarav 89
2 Diya 92
3 Kabir 76
Page 27 of 29
Program – 24
Aim: To update the marks of a student record in a MySQL table using Python.
Source Code:
import [Link]
conn = [Link](host="localhost", user="root",
password="yourpassword",
database="school")
cursor = [Link]()
[Link]("UPDATE student SET marks = %s WHERE rollno =
%s", (95, 2))
[Link]()
print([Link], "record(s) updated.")
[Link]()
Output:
1 record(s) updated.
Page 28 of 29
Program – 25
Aim: To delete a specific student record from a MySQL table using Python.
Source Code:
import [Link]
conn = [Link](host="localhost", user="root",
password="yourpassword",
database="school")
cursor = [Link]()
[Link]("DELETE FROM student WHERE rollno = %s", (3,))
[Link]()
print([Link], "record(s) deleted.")
[Link]()
Output:
1 record(s) deleted.
Page 29 of 29