INDIAN SCHOOL , AL AIN
ACADEMIC YEAR: 2025-26
PRACTICAL FILE
NAME : JONATHAN MATHEW LIJU
CLASS : XII B
SUBJECT : COMPUTER SCIENCE
Teacher In Charge: Mrs. JASEELA SEEYAD
INDIAN SCHOOL, AL AIN
GRADE XII (PRACTICALS) – 2025-26
SUB: COMPUTER SCIENCE
List of Programs
Unit Program Date
Of
Submission
I Programming and computational thinking 10/05/2025
Review of Python /Functions/Text File
1) Write a python program to search an element in a list and its location
using Linear search using a user-defined function. [The user should enter
the list and search element]
2) Write a random number generator that generates random numbers
between 1 and 6 (simulates a dice).
3) Write a program to take 10 sample fishing emails, and find the most
common word occurring.
4)
Write a menu-driven program to implement the following
functions.
a) Write a function write() in Python to write the following
multiple lines of text contents in to a text file
"Para.TXT"
"Whose woods these are I think I know
His house is in the village though
He will not see me stopping here
To watch his woods fill up with snow"
b) Write a function countH() in Python to display the number of
lines starting with 'H' in the file "Para.txt"
c) Write a function to read the text file line by line and
display each word separated by '#'
d) Write a function to read a text file and display the count of
vowels and consonants in the file.
5) Create a text file NOTES .TXT using a function create().WAF called
Rem_Lower(ifile, ofile) and read the text file and write the lines which are
starting with uppercase to the text file UPPER.TXT.
6) Create a text file TEST .TXT ,read and display the number of lowercase 21/06/2025
letters present in it .
7) Write a program to create a text file STORY.txt using a function
Create()and read and count the number of ‘my’ or ‘me’ words present
in it using function CountMeMy()
8) Write a function named filter(oldfile, newfile) that copies a text file
"source.txt" on to "target.txt" barring the lines starting with "@"
symbol. Read newfile using the function Readtarget()
Binary File 27/06/2025
9) Create a binary file “student.dat” with the structure[ name and roll
number, percentage] .Write a menu driven program to implement the
following functions:
1) Create
2) ReadAll
3) Search
4) Modify
5) Delete
10) A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price]. 27/06/2025
a. Write a user defined function CreateFile() to input data for a record and add to
Book.dat .
b. Write a function CountRec(Author) in Python which accepts the Author name as
parameter and count and return number of books by the given Author which are
stored in the binary file “Book.dat” Write a menu driven program and call the
functions.
CSV File 27/06/2025
11) A csv file has a structure[ name and roll number, marks].Create a menu
driven program and call the functions .
a. Create function addCsvFile () to write data in to the file
b. Create function readCsvFile() to read and display the data.
12) Write a Program in Python that defines and calls the following user defined
functions: (i) ADD() – To accept and add data of an employee to a CSV file
‘record.csv’. Each record consists of a list with field elements as empid,
name and mobile to store employee id, employee name and employee
salary respectively. (ii) COUNTR() – To count the number of records present
in the CSV file named ‘record.csv’
STACKS 2/09/2025
13) Write a menu-driven program with separate user-defined functions to
perform the following operations based on a list of integers.
a. Push the numbers into a stack.
b. Pop and display the content of the stack.
c. Display the stack status
14) Write a menu driven program to implement stack operations with a list of
employees having structure [eid,ename]
a. PUSH operation
b. POP operation
c. Display operation
15) Write a menu driven program to create a dictionary containing names and 11/10/2025
marks as key value pairs of 3 students. Write separate user defined
functions to perform the following operations:
a. Push the name and marks as key value pairs from the dictionary to
the stack.
b. Pop and display the content of the stack.
c. Display the Stack Status after each operation.
16) WAP to connect with database and create a student record [Rollno, Name,
Marks].Read and display all the records.
17) Input rollno search and display the record. If not found display Proper
message
18) Input rollno and update the and display the record. If not found display
Proper message
19) Input rollno delete the record. If not found display Proper message
20) Create a student table and insert data. Implement the following SQL 07/10/2025
commands on the student table:
ALTER table to add new attributes / modify data type / drop
Attribute
SELECT
UPDATE table to modify data
ORDER By to display data in ascending / descending order
DELETE to remove tuple(s)
GROUP BY and find the min, max, sum, count and average
Create another table parent and set Pcode as the primary key. Create
reference to the student table and show the output using equi- join and
natural join
1. Write a python program to search for an element in a
list and its location using Linear search using a user-
defined function. [The user should enter the list and
search element]
def isearch(list,item):
i=0
while i<len(list)and list[i]!=item:
i+=1
if i<len(list):
return i
else:
return False
print("insert array")
n=int(input("ENTER THE SIZE OF THE ARRAY"))
lst=[0]*n
for i in range(n):
lst[i]=int(input("enter the element"))
item=int(input("enter the iteam to be searched for"))
index=isearch(lst,item)
if index:
print("element found at",(index+1))
else:
print("Element not found")
INPUT
ENTER THE SIZE OF THE ARRAY: 5
enter the element: 10
enter the element: 20
enter the element: 30
enter the element: 40
enter the element: 50
enter the iteam to be searched for: 10
OUTPUT
element found at 1
RESULT: PROGRAM EXECUTED SUCCESSFULLY
2. Write a random number generator that generates random
numbers between 1 and 6 (simulates a dice). import random
import random
import time
print("Press Ctrl + C to stop the dice")
play = "y"
while play.lower() == "y":
try:
while True:
for i in range(10):
print()
n = random.randint(1, 6)
print(n, end="")
time.sleep(1)
except KeyboardInterrupt:
print("\nYour number is", n)
ans = input("Play more (y/n)? ")
if ans.lower() != "y":
play = "n"
break
OUTPUT
3
... [you press Ctrl+C]
your number is 1
play more(y/n)? y
RESULT: PROGRAM EXECUTED SUCCESSFULLY
3. Write a program to take 10 sample fishing emails, and find the
most common word occurring phishingemail=[
"jckpowin@loter.com",
"ackotwi@lottery.com",
"backpwi@lottery.com",
"zackotwin@lotry.com",
"lckpotin@lotty.com",
"kkpotwin@lottery.com",
"hakptwin@lottery.com",
"fackotwin@ltery.com",
"dackotin@lotey.com",
"cackpotwin@lotery.com"]
myd={}
for e in phishingemail:
x=e.split('@')
for w in x:
if w not in myd:
myd[w]=1
else:
myd[w]+=1
key_max=max(myd,key=myd.get)
print("most common occuring wordis:",key_max)
OUTPUT
most common occuring wordis: lottery.com
>>>
RESULT: PROGRAM EXECUTED SUCCESSFULLY
4. Write a menu-driven program to implement the
following functions.
a) Write a function write() in Python to write the
following multiple lines of text contents in to a text file
"Para.TXT"
"Whose woods these are I think I know
His house is in the village though
He will not see me stopping here
To watch his woods fill up with snow"
b) Write a function countH() in Python to display the
number of lines starting with 'H' in the file "Para.txt"
c) Write a function to read the text file line by line
and display each word separated by '#'
d) Write a function to read a text file and display the
count of vowels and consonants in the file.
def create():
ofile = open("para.txt", "a")
ofile.write("whose woods these are i think i know\n")
ofile.write("his house is in the village though\n")
ofile.write("he will not see me stopping here\n")
ofile.write("to watch his woods fill with snow\n")
ofile.close()
def countH():
ofile = open("para.txt", "r")
lines = ofile.readlines()
count = 0
for line in lines:
count += line.count('h') + line.count('H')
ofile.close()
print("Number of occurrences of 'h' or 'H':", count)
def hasHdisplay():
ofile = open("para.txt", "r")
print("Words separated by #:")
for line in ofile:
words = line.split()
for word in words:
print(word, end="#")
ofile.close()
def countuv():
ofile = open("para.txt", "r")
text = ofile.read()
ofile.close()
vcount = 0
ccount = 0
for ch in text:
if ch.lower() in "aeiou":
vcount += 1
elif ch.isalpha():
ccount += 1
print("The no. of vowels =", vcount)
print("The no. of consonants =", ccount)
while True:
print("\n1. create")
print("2. count 'h' or 'H'")
print("3. display words with #")
print("4. count vowels and consonants")
print("5. exit")
try:
ch = int(input("Enter your choice: "))
if ch == 1:
create()
elif ch == 2:
countH()
elif ch == 3:
hasHdisplay()
elif ch == 4:
countuv()
elif ch == 5:
break
else:
print("Invalid choice.")
except ValueError:
print("Please enter a valid number.")
OUTPUT
1. create
2. count 'h' or 'H'
3. display words with #
4. count vowels and consonants
5. exit
Enter your choice: 2
Number of occurrences of 'h' or 'H': 7
Enter your choice: 3
Words separated by #:
whose#woods#these#are#i#think#i#know#his#house#is#in#the#villa
ge#though#...
RESULT: PROGRAM EXECUTED SUCCESSFULLY
5. Create a text file NOTES .TXT using a function
create().WAF called Rem_Lower(ifile, ofile) and read the
text file and write the lines which are starting with
uppercase to the text file UPPER.TXT.
def create():
ifile=open("NOTES.TXT","w")
ifile.close()
def Rem_Lower(ifile, ofile):
fin=open(ifile,"r")
fout=open(ofile,"w")
for line in fin:
if line[0].isupper():
fout.write(line)
fin.close()
fout.close()
create()
Rem_Lower("NOTES.TXT","UPPER.TXT")
INPUT
This is the first line
hello world
Python is powerful
java is case-sensitive
Computer Science is fun
coding is creative
OUTPUT
This is the first line
Python is powerful
Computer Science is fun
RESULT: PROGRAM EXECUTED SUCCESSFULLY
6. Create a text file TEST .TXT ,read and display the
number of lowercase letters present in it .
ifile=open("TEST.TXT","r")
text=ifile.read()
count=0
for ch in text:
if ch.islower():
count+=1
print("number of lowercase letters are",count)
ifile.close()
INPUT
Hello World
Python Is Fun
coding in CBSE
OUTPUT
number of lowercase letters are 20
RESULT: PROGRAM EXECUTED SUCCESSFULLY
7. Write a program to create a text file STORY.txt using
a function Create () and read and count the number of
‘my’ or ‘me’ words present in it using function
CountMeMy()
def create():
ofile=open("story.txt","w")
while True:
line=input("enter a line: ")
ofile.write(line+"\n")
choice=input("enter continue y/n: ")
if choice=="n":
break
ofile.close()
def countmemy():
count=0
ifile=open("story.txt","r")
n=ifile.read()
word=n.split()
for x in word:
if x=="me" or x=="my":
count+=1
print("number of me or my is",count)
ifile.close()
create()
countmemy()
INPUT
enter a line: my name is John
enter continue y/n: y
enter a line: he told me the truth
enter continue y/n: y
enter a line: this is my book
enter continue y/n: n
OUTPUT
number of me or my is 3
def filter(oldfile,newfile):
ifile=open(oldfile,"r")
ofile=open(newfile,"w")
for line in ifile:
if line.strip()!="" and line[0]!="@":
ofile.write(line)
ifile.close()
ofile.close()
RESULT: PROGRAM EXECUTED SUCCESSFULLY
8. Write a function named filter(oldfile, newfile) that
copies a text file "source.txt" on to "target.txt" barring
the lines starting with "@" symbol. Read newfile using
the function Readtarget()
old_file=input("enter the old file name: ")
new_file=input("enter the new file name: ")
filter(old_file,new_file)
INPUT
enter the old file name: data.txt
enter the new file name: clean.txt
OUTPUT
Hello world
Python is fun
AI is amazing
import pickle
RESULT: PROGRAM EXECUTED SUCCESSFULLY
Binary File
9. Create a binary file “student.dat” with the
structure[ name and roll number, percentage] .Write a
menu driven program to implement the following
functions:
1) Create
2) ReadAll
3) Search
4) Modify
5) Delete
def create():
ifile = open("student.dat", "ab")
name = input("enter the name: ")
roll = int(input("enter the roll no: "))
per = int(input("enter the percentage: "))
pickle.dump([name, roll, per], ifile)
ifile.close()
def readall():
ifile = open("student.dat", "rb")
try:
while True:
data = pickle.load(ifile)
print(data)
except EOFError:
ifile.close()
def search():
name = input("enter the name to be searched: ")
ifile = open("student.dat", "rb")
found = False
try:
while True:
data = pickle.load(ifile)
if data[0] == name:
print(data)
found = True
except EOFError:
ifile.close()
if not found:
print("student not found")
def modify():
name = input("enter the name to be modified: ")
per = int(input("enter the new percentage: "))
students = []
modified = False
ifile = open("student.dat", "rb")
try:
while True:
student = pickle.load(ifile)
if student[0] == name:
student[2] = per
modified = True
students.append(student)
except EOFError:
ifile.close()
if modified:
ifile = open("student.dat", "wb")
for s in students:
pickle.dump(s, ifile)
ifile.close()
print("record modified successfully!")
else:
print("student not found")
def delete():
roll = int(input("enter roll number to be deleted: "))
student_found = False
students = []
ifile = open("student.dat", "rb")
try:
while True:
student = pickle.load(ifile)
if student[1] != roll:
students.append(student)
else:
student_found = True
except EOFError:
ifile.close()
if student_found:
ifile = open("student.dat", "wb")
for s in students:
pickle.dump(s, ifile)
ifile.close()
print("record deleted successfully!")
else:
print("student not found")
OUTPUT
Menu
1. create
2. read all
3. search
4. modify
5. delete
6. exit
Enter choice: 1
enter the name: John
enter the roll no: 101
enter the percentage: 85
Enter choice: 1
enter the name: Alice
enter the roll no: 102
enter the percentage: 92
Enter choice: 2
['John', 101, 85]
['Alice', 102, 92]
Enter choice: 4
enter the name to be modified: John
enter the new percentage: 90
record modified successfully!
Enter choice: 2
['John', 101, 90]
['Alice', 102, 92]
Enter choice: 5
enter roll number to be deleted: 102
record deleted successfully!
Enter choice: 2
['John', 101, 90]
Enter choice: 6
RESULT: PROGRAM EXECUTED SUCCESSFULLY
10. A binary file Book.dat has structure [BookNo,
Book_Name, Author, Price].
Write a menu-driven Python program to:
a) CreateFile() – Input a book record and add to
Book.dat.
b) CountRec(Author) – Count and return the number of
books by a given author in Book.dat.
import pickle
def CreateFile():
ifile = open("book.dat", "ab")
bookNo = int(input("enter the book No: "))
book_name = input("enter the name of the book: ")
author = input("enter the name of the author: ")
price = int(input("enter the price: "))
Book = [bookNo, book_name, author, price]
pickle.dump(Book, ifile)
ifile.close()
def countRec(author):
ifile = open("book.dat", "rb")
count = 0
try:
while True:
book = pickle.load(ifile)
if book[2] == author:
count += 1
except EOFError:
if count == 0:
print("no author found")
else:
print("the number of books =", count)
ifile.close()
while True:
print("menu")
print("1. create")
print("2. count")
print("3. exit")
choice = int(input("enter your choice: "))
if choice == 1:
CreateFile()
elif choice == 2:
author = input("enter the author: ")
countRec(author)
elif choice == 3:
break
else:
print("invalid choice")
OUTPUT
menu
1. create
2. count
3. exit
enter your choice: 1
enter the book No: 101
enter the name of the book: Python Basics
enter the name of the author: John
enter the price: 300
menu
1. create
2. count
3. exit
enter your choice: 1
enter the book No: 102
enter the name of the book: Python Advanced
enter the name of the author: John
enter the price: 500
menu
1. create
2. count
3. exit
enter your choice: 2
enter the author: John
the number of books = 2
menu
1. create
2. count
3. exit
enter your choice: 3
RESULT: PROGRAM EXECUTED SUCCESSFULLY
11. A csv file has a structure[ name and roll number,
marks].Create a menu driven program and call the
functions .
a. Create function addCsvFile () to write data in to the
file
b. Create function readCsvFile() to read and display
the data.
import csv
def addcsvfile():
ifile = open("student.csv", "a", newline="")
writer = csv.writer(ifile)
ch = "y"
while ch.lower() == "y":
name = input("Enter the name: ")
roll = int(input("Enter the roll no: "))
marks = int(input("Enter the marks: "))
stud = [name, roll, marks]
writer.writerow(stud)
ch = input("Do you want to continue? (y/n): ")
ifile.close()
def readcsvfile():
ifile = open("student.csv", "r")
reader = csv.reader(ifile)
for i in reader:
if len(i) == 3:
print("Name:", i[0])
print("Roll no:", i[1])
print("Marks:", i[2])
print("-" * 20)
else:
print("Error: row is incomplete or malformed")
ifile.close()
while True:
print("Menu")
print("1. Add student records")
print("2. Read student records")
print("3. Exit")
choice = int(input("Enter choice: "))
if choice == 1:
addcsvfile()
elif choice == 2:
readcsvfile()
elif choice == 3:
break
else:
print("Invalid choice")
INPUT
Enter the name: John
Enter the roll no: 101
Enter the marks: 85
Do you want to continue? (y/n): y
Enter the name: Alice
Enter the roll no: 102
Enter the marks: 92
Do you want to continue? (y/n): n
OUTPUT
Name: John
Roll no: 101
Marks: 85
--------------------
Name: Alice
Roll no: 102
Marks: 92
RESULT: PROGRAM EXECUTED SUCCESSFULLY
12. Write a Program in Python that defines and calls the
following user defined functions: (i) ADD() – To accept
and add data of an employee to a CSV file ‘record.csv’.
Each record consists of a list with field elements as
empid, name and mobile to store employee id, employee
name and employee salary respectively. (ii) COUNTR() –
To count the number of records present in the CSV file
named ‘record.csv’
import csv
def ADD():
ifile = open("record.csv", "a", newline="")
writer = csv.writer(ifile)
ch = "y"
while ch.lower() == "y":
empid = input("Enter employee id: ")
name = input("Enter employee name: ")
mobile = input("Enter employee mobile: ")
record = [empid, name, mobile]
writer.writerow(record)
ch = input("Do you want to continue? (y/n): ")
ifile.close()
def COUNTR():
try:
ifile = open("record.csv", "r")
reader = csv.reader(ifile)
count = 0
for row in reader:
if len(row) == 3:
count += 1
print("Number of employee records:", count)
ifile.close()
except FileNotFoundError:
print("File 'record.csv' not found. Please add records first.")
while True:
print("Menu")
print("1. Add employee record")
print("2. Count records")
print("3. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
ADD()
elif choice == 2:
COUNTR()
elif choice == 3:
break
else:
print("Invalid choice")
INPUT
Enter employee id: E101
Enter employee name: John
Enter employee mobile: 9876543210
Do you want to continue? (y/n): y
Enter employee id: E102
Enter employee name: Alice
Enter employee mobile: 8765432109
Do you want to continue? (y/n): n
Output :-
Number of employee records: 2
RESULT: PROGRAM EXECUTED SUCCESSFULLY
STACKS
13. Write a menu-driven program with separate user-
defined functions to perform the following operations
based on a list of integers.
a. Push the numbers into a stack.
b. Pop and display the content of the stack.
c. Display the stack status
stak=[]
top=None
def push(stak, item):
stak.append(item)
top = len(stak)-1
def pop(stak):
if stak==[]:
return None
else:
return stak.pop()
def peek(stak):
if stak==[]:
return "understood"
else:
top = len(stak)-1
print(stak[top])
def display(stak):
if stak==[]:
print("underflow")
else:
top=len(stak)-1
print(stak[top], "----top")
for i in range(top-1, -1, -1):
print(stak[i])
while True:
choice = int(input("Enter choice:"))
print(“1.push”)
print(“2.pop”)
print("3.peek”)
print(“4.display”)
if choice == 1:
item = int(input("Enter the item: "))
push(stak, item)
elif choice == 2:
print("Popped", pop(stak))
elif choice == 3:
peek(stak)
elif choice == 4:
display(stak)
else:
break
OUTPUT
Menu
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter choice: 1
Enter the item: 10
10 pushed to stack
Enter choice: 1
Enter the item: 20
20 pushed to stack
Enter choice: 4
20 ----top
10
Enter choice: 3
Top element: 20
Enter choice: 2
Popped: 20
Enter choice: 4
10 ----top
RESULT: PROGRAM EXECUTED SUCCESSFULLY
14. Write a menu driven program to implement stack
operations with a list of employees having structure
[eid,ename]
a. PUSH operation
b. POP operation
c. Display operation
emp=[]
top=None
while True:
print("menu")
print(“push”)
print("pop")
print("display")
print("exit")
choice = int(input("Enter choice: "))
if choice == 1:
eid=int(input("enter the item"))
name=input("enter emploee name:")
e=(eid,name)
emp.append(e)
elif choice == 2:
if emp==[]:
print("empty stack")
else:
print(emp.pop())
elif choice == 3:
top=len(emp)
for i in range(top-1,-1,-1):
print(emp[i])
elif choice == 4:
break
else:
print("wrong choice")
OUTPUT
Menu
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter choice: 1
Enter the item: 10
10 pushed to stack
Enter choice: 1
Enter the item: 20
20 pushed to stack
Enter choice: 4
20 ----top
10
Enter choice: 3
Top element: 20
Enter choice: 2
Popped: 20
Enter choice: 4
10 ----top
RESULT: PROGRAM EXECUTED SUCCESSFULLY
15. Write a menu driven program to create a dictionary
containing names and marks as key value pairs of 3
students. Write separate user defined functions to
perform the following operations:
a. Push the name and marks as key value pairs from
the dictionary to the stack.
b. Pop and display the content of the stack.
c. Display the Stack Status after each operation.
student = {}
stk = []
top = None
for i in range(6):
name = input("enter the student name: ")
marks = float(input("enter the student marks: "))
student[name] = marks
def push(stk, item):
stk.append(item)
top = len(stk) - 1
def pop(stk):
if stk == []:
return None
else:
return stk.pop()
def display(stk):
if stk == []:
print("underflow")
else:
top = len(stk) - 1
print(stk[top], "----top")
for i in range(top - 1, -1, -1):
print(stk[i])
while True:
choice = int(input("Enter choice: "))
if choice == 1:
for i in student:
if student[i] > 75:
push(stk, i)
elif choice == 2:
popped = pop(stk)
if popped is None:
print("stack is empty, nothing to pop.")
else:
print("Popped:", popped)
elif choice == 3:
display(stk)
elif choice == 4:
break
else:
print("invalid choice")
OUTPUT
Enter the student name: John
Enter the student marks: 80
Enter the student name: Alice
Enter the student marks: 72
Enter the student name: Bob
Enter the student marks: 90
Enter the student name: Eve
Enter the student marks: 68
Enter the student name: Mike
Enter the student marks: 78
Enter the student name: Sara
Enter the student marks: 65
Menu
1. Push students with marks > 75
2. Pop student
3. Display stack
4. Exit
Enter choice: 1
John pushed to stack
Bob pushed to stack
Mike pushed to stack
Enter choice: 3
Mike ----top
Bob
John
Enter choice: 2
Popped: Mike
Enter choice: 3
Bob ----top
John
RESULT: PROGRAM EXECUTED SUCCESSFULLY
16. WAP to connect with database and create a student
record [Rollno, Name,
Marks].Read and display all the records.
import mysql.connector as sqltor
mycon = sqltor.connect( host="localhost", user="root",
password="Isalain", database="student")
cursor = mycon.cursor()
sql = "CREATE TABLE student (Rollo INT, name VARCHAR(20), marks INT)"
cursor.execute(sql)
mycon.commit()
print("Table created")
sql = "SELECT * FROM student"
cursor.execute(sql)
for i in cursor:
print(i)
mycon.close()
INPUT
INSERT INTO student (Rollo, name, marks) VALUES (101, 'John', 85);
INSERT INTO student (Rollo, name, marks) VALUES (102, 'Alice', 90);
OUTPUT
(101, 'John', 85)
(102, 'Alice', 90)
RESULT: PROGRAM EXECUTED SUCCESSFULLY
17. Input rollno search and display the record. If not
found display Proper message
import mysql.connector as sqltor
mycon =
sqltor.connect( host="localhost",user="root",password="Isalain",databas
e="student")
cursor = mycon.cursor()
rollno = int(input("Enter the roll no to be searched: "))
cursor.execute("SELECT * FROM student WHERE Rollo =
{}".format(rollno))
found = False
for i in cursor:
print(i)
found = True
if not found:
print("RECORD not found")
mycon.close()
OUTPUT
Enter the roll no to be searched: 101
(101, 'John', 85)
RESULT: PROGRAM EXECUTED SUCCESSFULLY
18. Input rollno and update the and display the record.
If not found display Proper message
import mysql.connector as sqltor
mycon = sqltor.connect(
host="localhost",
user="root",
password="Isalain",
database="student")
cursor = mycon.cursor()
rollno = int(input("Enter the roll no to be updated: "))
marks = int(input("Enter the new marks: "))
cursor.execute("SELECT * FROM student WHERE Rollo =
{}".format(rollno))
record = cursor.fetchone()
if record:
cursor.execute("UPDATE student SET marks = {} WHERE Rollo =
{}".format(marks, rollno))
mycon.commit()
print("Record updated successfully")
cursor.execute("SELECT * FROM student WHERE Rollo =
{}".format(rollno))
updated_record = cursor.fetchone()
print("Updated Record:", updated_record)
else:
print("Record not found")
mycon.close()
OUTPUT
Enter the roll no to be updated: 101
Enter the new marks: 95
Record updated successfully
Updated Record: (101, 'John', 95)
RESULT: PROGRAM EXECUTED SUCCESSFULLY
19. Input rollno delete the record. If not found display
Proper message
import mysql.connector as sqltor
mycon = sqltor.connect(
host="localhost",
user="root",
password="Isalain",
database="student")
cursor = mycon.cursor()
rollno = int(input("Enter the roll no to be deleted: "))
cursor.execute("SELECT * FROM student WHERE Rollo =
{}".format(rollno))
record = cursor.fetchone()
if record:
cursor.execute("DELETE FROM student WHERE Rollo =
{}".format(rollno))
mycon.commit()
print("Record deleted successfully")
else:
print("Record not found")
mycon.close()
OUTPUT
Enter the roll no to be deleted: 101
Record deleted successfully
RESULT: PROGRAM EXECUTED SUCCESSFULLY
20.Create a student table and insert data. Implement the following SQL
commands on the student table:
ALTER table to add new attributes / modify data type / drop
Attribute
SELECT
UPDATE table to modify data
ORDER By to display data in ascending / descending order
DELETE to remove tuple(s)
GROUP BY and find the min, max, sum, count and average
Create another table parent and set Pcode as the primary key. Create
reference to the student table and show the output using equi- join and
natural join
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| studentrecords |
| sys |
+--------------------+
5 rows in set (0.00 sec)
mysql> USE studentrecords;
Database changed
mysql> CREATE TABLE student(Roll INT PRIMARY KEY,Name
VARCHAR(24),Marks INT);
Query OK, 0 rows affected (0.09 sec)
mysql> INSERT INTO student VALUES(20,'ibad',100),
Query OK, 1 row affected (0.03 sec)
mysql> INSERT INTO student VALUES(10,'Jonathan',100),
-> (22,'Felix',99);
Query OK, 2 rows affected (0.02 sec)
mysql> SELECT*FROM student;
+------+--------+-------+
| Roll | Name | Marks |
+------+--------+-------+
| 10 | Jonathan | 100 |
| 20 | ibad | 100 |
| 22 | Felix | 99 |
+------+--------+-------+
3 rows in set (0.00 sec)
mysql> ALTER TABLE student add(class varchar(3));
Query OK, 0 rows affected (0.03 sec)
mysql> desc student;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| Roll | int | NO | PRI | NULL | |
| Name | varchar(24) | YES | | NULL | |
| Marks | int | YES | | NULL | |
| class | varchar(3) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
4 rows in set (0.03 sec)
mysql> ALTER TABLE student MODIFY column class varchar(10);
Query OK, 0 rows affected (0.03 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc student;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| Roll | int | NO | PRI | NULL | |
| Name | varchar(24) | YES | | NULL | |
| Marks | int | YES | | NULL | |
| class | varchar(10) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
mysql> ALTER TABLE student DROP COLUMN class;
Query OK, 0 rows affected (0.04 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc student;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| Roll | int | NO | PRI | NULL | |
| Name | varchar(24) | YES | | NULL | |
| Marks | int | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
mysql> SELECT*FROM student;
+------+--------+-------+
| Roll | Name | Marks |
+------+--------+-------+
| 10 | Jonathan | 100 |
| 20 | ibad | 100 |
| 22 | Felix | 99 |
+------+--------+-------+
3 rows in set (0.00 sec)
mysql> UPDATE student SET Marks=70 WHERE Roll=10;
Query OK, 1 row affected (0.03 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> SELECT*FROM student;
+------+--------+-------+
| Roll | Name | Marks |
+------+--------+-------+
| 10 | Jonathan | 70 |
| 20 | ibad | 100 |
| 22 | Felix | 99 |
+------+--------+-------+
3 rows in set (0.00 sec)
mysql> SELECT*FROM student ORDER BY Marks asc;
+------+--------+-------+
| Roll | Name | Marks |
+------+--------+-------+
| 10 | Jonathan | 70 |
| 22 | Felix | 99 |
| 20 | ibad | 100 |
+------+--------+-------+
3 rows in set (0.00 sec)
mysql> DELETE FROM student WHERE Roll=10;
Query OK, 1 row affected (0.03 sec)
mysql> SELECT*FROM student;
+------+--------+-------+
| Roll | Name | Marks |
+------+--------+-------+
| 20 | ibad | 100 |
| 22 | Felix | 99 |
+------+--------+-------+
2 rows in set (0.00 sec)
mysql> SELECT Name,Count(*) FROM student GROUP BY Name;
+--------+----------+
| Name | Count(*) |
+--------+----------+
| ibad | 1|
| Felix | 1|
+--------+----------+
2 rows in set (0.00 sec)
mysql> SELECT max(Marks) "Maximum marks" FROM student;
+---------------+
| Maximum marks |
+---------------+
| 100 |
+---------------+
1 row in set (0.00 sec)
mysql> SELECT min(Marks) "Minimum marks" FROM student;
+---------------+
| Minimum marks |
+---------------+
| 99 |
+---------------+
1 row in set (0.00 sec)
mysql> SELECT count(Roll) "No.of students" FROM student;
+----------------+
| No.of students |
+----------------+
| 2|
+----------------+
1 row in set (0.02 sec)
mysql> SELECT sum(Marks) "Sum",avg(Marks) "Average" FROM student;
+------+---------+
| Sum | Average |
+------+---------+
| 199 | 99.5000 |
+------+---------+
1 row in set (0.00 sec)
mysql> UPDATE student SET Pcode=3660 WHERE Roll=20;
Query OK, 1 row affected (0.04 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> UPDATE student SET Pcode=5678 WHERE Roll=22;
Query OK, 1 row affected (0.02 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> SELECT*FROM student;
+------+--------+-------+-------+
| Roll | Name | Marks | Pcode |
+------+--------+-------+-------+
| 20 | ibad | 100 | 3660 |
| 22 | Felix | 99 | 5678 |
+------+--------+-------+-------+
2 rows in set (0.00 sec)
mysql> CREATE TABLE Parent(Pcode INT PRIMARY KEY,Name
VARCHAR(20),Salary INT);
Query OK, 0 rows affected (0.07 sec)
mysql> INSERT INTO Parent VALUES(3660,'Azim',20000),
-> (5678,'Sebastian',10000);
Query OK, 2 rows affected (0.02 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> select*from Parent;
+-------+--------+--------+
| Pcode | Name | Salary |
+-------+--------+--------+
| 3660 | Azim | 20000 |
| 5678 | Sebastian | 10000 |
+-------+--------+--------+
2 rows in set (0.00 sec)
mysql> SELECT*FROM student JOIN Parent ON student.Pcode=Parent.Pcode;
+------+--------+-------+-------+-------+--------+--------+
| Roll | Name | Marks | Pcode | Pcode | Name | Salary |
+------+--------+-------+-------+-------+--------+--------+
| 20 | ibad | 100 | 3660 | 3660 | Azim | 20000 |
| 22 | Felix | 99 | 5678 | 5678 | Sebastian | 10000 |
+------+--------+-------+-------+-------+--------+--------+
2 rows in set (0.00 sec)
RESULT: PROGRAM EXECUTED SUCCESSFULLY