Class 12 CS Practical List 2023-24
Class 12 CS Practical List 2023-24
Class 12 CS Practical List 2023-24
22 Perform all the operations with reference to table ‘students’ through MySQL-
Python connectivity.
23` Write a menu-driven program to store data into a MySQL database named shop and
table customer as following:
1. Add customer details
2. Update customer details
3. Delete customer details
4. Display all customer details
PART 4 MYSQL QUERIES
1. Consider the following MOVIE table and write the SQL queries based on it.
Movie_ID MovieName Type ReleaseDate ProductionCost BusinessCost
M001 Dahek Action 2022/01/26 1245000 1300000
M002 Attack Action 2022/01/28 1120000 1250000
M003 Looop Lapeta Thriller 2022/02/01 250000 300000
M004 Badhai Do Drama 2022/02/04 720000 68000
M005 Shabaash Mithu Biography 2022/02/04 1000000 800000
d) As per the preferences of the students four teams were formed as given below. Insert these
four rows in TEAM table:
a. Row 1: (1, Tehlka)
b. Row 2: (2, Toofan)
c. Row 3: (3, Aandhi)
d. Row 3: (4, Shailab)
• Create
a table students with the specifications - ROLLNO integer, STNAME character(10)
in MySQL and perform the following operations:
o Insert two records in it
o Display the contents of the table
2. Perform all the operations with reference to table ‘students’ through MySQL-Python
connectivity.
3. Write a menu-driven program to store data into a MySQL database named shop and
table customer as following:
a) Add customer details
SOLUTIONS
Part 1: working with functions
1. Write a python program using a function to print factorial number series from n to
m numbers.
def facto():
n=int(input("Enter the number:"))
f=1
for i in range(1,n+1):
f*=i
print("Factorial of ",n, "is: ",f, end=" ")
facto()
2. Write a python program to accept the username "Admin" as the default argument
and password 123 entered by the user to allow login into the system.
def user_pass(password,username="Admin"):
if password=='123':
print("You have logged into system")
else:
print("Password is incorrect!!!!!!")
sum10(1,2,3,4,5,6,7,8,9,10)
def product10(*n):
pr=1
for i in n:
pr=pr * i
print("Product of first 10 Numbers:",pr)
product10(1,2,3,4,5,6,7,8,9,10)
Part 2: Data File Handling
4. Create a text file "intro.txt" in python and ask the user to write a single line of text
by user input.
def singleLineText():
f = open("intro.txt","w")
text=input("Enter the text:")
f.write(text)
f.close( )
singleLineText ()
5. Write a program to count a total number of lines and count the total number of lines
starting with 'A', 'B', and 'C' from the file dfh.txt.
def program5():
with open("MyFile.txt","r") as f1:
data=f1.readlines()
cnt_lines=0
cnt_A=0
cnt_B=0
cnt_C=0
for lines in data:
cnt_lines+=1
if lines[0]=='A':
cnt_A+=1
if lines[0]=='B':
cnt_B+=1
if lines[0]=='C':
cnt_C+=1
print("Total Number of lines are:",cnt_lines)
print("Total Number of lines strating with A are:",cnt_A)
print("Total Number of lines strating with B are:",cnt_B)
print("Total Number of lines strating with C are:",cnt_C)
program5()
6. Write a program to replace all spaces from text with - (dash) from the file intro.txt
def program6():
cnt = 0
with open("intro.txt","r") as f1:
data = f1.read()
data=data.replace(' ','-')
with open("intro.txt","w") as f1:
f1.write(data)
with open("intro.txt","r") as f1:
print(f1.read())
program6()
7. Write a program to know the cursor position and print the text according to the
below-given specifications:
a) Print the initial position
b) Move the cursor to 4th position
c) Display next 5 characters
d) Move the cursor to the next 10 characters
e) Print the current cursor position
f) Print next 10 characters from the current cursor position
def program7():
f = open("intro.txt","r")
print("Cusror initial position.")
print(f.tell())
f.seek(4,0)
print("Displaying values from 5th position.")
print(f.read(5))
f.seek(10,0)
print(f.tell())
print("Print cursor's current postion")
print(f.seek(7,0))
print("Displaying next 10 characters from cursor's current postion.")
print(f.read(10))
f.close()
program7()
8. Write a program to store customer data into a binary file cust.dat using a dictionary
and print them on screen after reading them. The customer data contains ID as key,
and name, city as values.
import pickle
rec={}
def file_create():
f=open("client.dat","wb")
cno = int(input("Enter Client ID:"))
cname = input("Enter Client Name:")
address = input("Enter Address:")
rec={cno:[cname,address]}
pickle.dump(rec,f)
def read_data():
f = open("client.dat","rb")
print(“*” * 78)
print("Data stored in File....")
rec=pickle.load(f)
for i in rec:
print(rec[i])
file_create()
read_data()
9. Write a program to update a record from student.dat file by its rollno. Display
the updated record on screen.
Ans. import pickle as p
rec=[]
found=0
f=open("student.dat","rb+")
r=p.load(f)
print("Existing Record:",r)
ro=int(input("Enter roll no to update:"))
for i in r:
if ro==i[0]:
i[1]=input("Enter new name:")
found=1
break
if found==0:
print("record not found..")
else:
f.seek(0)
p.dump(r,f)
print('Record Updated...')
f.close()
f1=open('student.dat','rb+')
r=p.load(f1)
print("Updated Record:",r)
f1.close()
10. Write a program to write data into binary file marks.dat and display the
records of students who scored more than 95 marks.
Ans. import pickle
def search_95plus():
f = open("marks.dat","ab")
while True:
rn=int(input("Enter the rollno:"))
sname=input("Enter the name:")
marks=int(input("Enter the marks:"))
rec=[]
data=[rn,sname,marks]
rec.append(data)
pickle.dump(rec,f)
ch=input("Wnat more records?Yes:")
if ch.lower() not in 'yes':
break
f.close()
f = open("marks.dat","rb")
cnt=0
try:
while True:
data = pickle.load(f)
for s in data:
if s[2]>95:
cnt+=1
print("Record:",cnt)
print("RollNO:",s[0])
print("Name:",s[1])
print("Marks:",s[2])
except Exception:
f.close()
search_95plus()
11. Read a CSV file top5.csv and print the contents in a proper format. The data for
top5.csv file are as following:
SNo Batsman Team Runs Highest
12. Read a CSV file top5.csv and print them with tab delimiter. Ignore first row header
to print in tabular form.
Ans. from csv import reader
def pro12():
f = open("e:\\top5.csv","r")
dt = reader(f,delimiter=',')
headr_row=next(dt)
data = list(dt)
f.close()
for i in data:
for j in i:
print(j,"\t",end=" ")
print()
pro12()
13. Read a CSV file students.csv and print them with tab delimiter. Ignore first row
header to print in tabular form.
Field 1 Data Type
StudentID Integer
StudentName String
Score Integer
Ans. from csv import writer
def pro13():
#Create Header First
f = open("result.csv","w",newline='\n')
dt = writer(f)
dt.writerow(['Student_ID','StudentName','Score'])
f.close()
#Insert Data
f = open("result.csv","a",newline='\n')
while True:
st_id= int(input("Enter Student ID:"))
st_name = input("Enter Student name:")
st_score = input("Enter score:")
dt = writer(f)
dt.writerow([st_id,st_name,st_score])
ch=input("Want to insert More records?(y or Y):")
ch=ch.lower()
if ch !='y':
break
print("Record has been added.")
f.close()
pro13()
Part 3 Data Structure
14. Write a menu-driven python program to implement stack operation.
Ans. def check_stack_isEmpty(stk):
if stk==[]:
return True
else:
return False
# An empty list to store stack elements, initially empty
s=[]
top = None # This is top pointer for push and pop
def main_menu():
while True:
print("Stack Implementation")
print("1 - Push")
print("2 - Pop")
print("3 - Peek")
print("4 - Display")
print("5 - Exit")
ch = int(input("Enter the your choice:"))
if ch==1:
el = int(input("Enter the value to push an element:"))
push(s,el)
elif ch==2:
e=pop_stack(s)
if e=="UnderFlow":
print("Stack is underflow!")
print("Element popped:",e)
elif ch==3:
e=pop_stack(s)
if e=="UnderFlow":
print("Stack is underflow!")
else:
print("The element on top is:",e)
elif ch==4:
display(s)
elif ch==5:
break
else:
print("Sorry,invalid option")
def push(stk,e):
stk.append(e)
top = len(stk)-1
def display(stk):
if check_stack_isEmpty(stk):
print("Stack is Empty")
else:
top = len(stk)-1
print(stk[top],"-Top")
for i in range(top-1,-1,-1):
print(stk[i])
def pop_stack(stk):
if check_stack_isEmpty(stk):
return "UnderFlow"
else:
e = stk.pop()
if len(stk)==0:
top = None
else:
top = len(stk)-1
return e
def peek(stk):
if check_stack_isEmpty(stk):
return "UnderFlow"
else:
top = len(stk)-1
return stk[top]
15. Write a program to implement a stack for the employee details (empno, name).
Ans. stk=[]
top=-1
def line():
print('~'*100)
def isEmpty():
global stk
if stk==[]:
print("Stack is empty!!!")
else:
None
def push():
global stk
global top
empno=int(input("Enter the employee number to push:"))
ename=input("Enter the employee name to push:")
stk.append([empno,ename])
top=len(stk)-1
def display():
global stk
global top
if top==-1:
isEmpty()
else:
top=len(stk)-1
print(stk[top],"<-top")
for i in range(top-1,-1,-1):
print(stk[i])
def pop_ele():
global stk
global top
if top==-1:
isEmpty()
else:
stk.pop()
top=top-1
def main():
while True:
line()
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")
ch=int(input("Enter your choice:"))
if ch==1:nm
push()
print("Element Pushed")
elif ch==2:
pop_ele()
elif ch==3:
display()
elif ch==4:
break
else:
print("Invalid Choice")
16. Write a python program to check whether a string is a palindrome or not using
stack.
Ans.
stack = []
top = -1
# push function
def push(ele):
global top
top += 1
stack[top] = ele
# pop function
def pop():
global top
ele = stack[top]
top -= 1
return ele
# Function that returns 1 if string is a palindrome
def isPalindrome(string):
global stack
length = len(string)
# Allocating the memory for the stack
stack = ['0'] * (length + 1)
# Finding the mid
mid = length // 2
i=0
while i < mid:
push(string[i])
i += 1
# Checking if the length of the string is odd then neglect the middle
#character
if length % 2 != 0:
i += 1
# While not the end of the string
while i < length:
ele = pop()
# If the characters differ then the given string is not a palindrome
if ele != string[i]:
return False
i += 1
return True
string = input("Enter string to check:")
if isPalindrome(string):
print("Yes, the string is a palindrome")
else:
print("No, the string is not a palindrome")
3. Suppose your school management has decided to conduct cricket matches between
students of Class XI and Class XII. Students of each class are asked to join any one of
the four teams – Team Titan, Team Rockers, Team Magnet and Team Hurricane.
During summer vacations, various matches will be conducted between these teams.
Help your sports teacher to do the following:
d) As per the preferences of the students four teams were formed as given below. Insert these
four rows in TEAM table:
a. Row 1: (1, Tehlka)
b. Row 2: (2, Toofan)
c. Row 3: (3, Aandhi)
d. Row 3: (4, Shailab)
Answers:
a) create database sports;
c) desc team;
Inserting data:
mqsql> insert into team values(1,'Tehlka');
Show the content of table - team:
select * from team;
Creating another table:
create table match_details
-> (matchid varchar(2) primary key,
-> matchdate date,
-> firstteamid int(1) references team(teamid),
-> secondteamid int(1) references team(teamid),
-> firstteamscore int(3),
-> secondteamscore int(3));
4. Write following queries:
a) Display the matchid, teamid, teamscore who scored more than 70 in first inning along
with team name.
b) Display matchid, teamname and secondteamscore between 100 to 160.
c) Display matchid, teamnames along with matchdates.
d) Display unique team names
e) Display matchid and matchdate played by Aandhi and Shailab.
Answers:
a) select match_details.matchid, match_details.firstteamid,
team.teamname,match_details.firstteamscore from match_details,
team where match_details.firstteamid = team.teamid and
match_details.firstteamscore>70;
2. using mysqlconnector
import mysql.connector as ms
db=ms.connect(host="localhost",user="root",passwd="password",database='school')
cn=db.cursor()
def insert_rec():
try:
while True:
rn=int(input("Enter roll number:"))
sname=input("Enter name:")
marks=float(input("Enter marks:"))
gr=input("Enter grade:")
cn.execute("insert into students
values({},'{}',{},'{}')".format(rn,sname,marks,gr))
db.commit()
ch=input("Want more records? Press (N/n) to stop entry:")
if ch in 'Nn':
break
except Exception as e:
print("Error", e)
def update_rec():
try:
rn=int(input("Enter rollno to update:"))
marks=float(input("Enter new marks:"))
gr=input("Enter Grade:")
cn.execute("update students set marks={},grade='{}' where
rno={}".format(marks,gr,rn))
db.commit()
except Exception as e:
print("Error",e)
def delete_rec():
try:
rn=int(input("Enter rollno to delete:"))
cn.execute("delete from students where rno={}".format(rn))
db.commit()
except Exception as e:
print("Error",e)
def view_rec():
try:
cn.execute("select * from students")
data=cn.fetchall()
for i in data:
print(i)
except Exception as e:
print("Error",e)
while True:
print("MENU\n1. Insert Record\n2. Update Record \n3. Delete Record\n4.
Display Record \n5. Exit")
ch=int(input("Enter your choice<1-4>="))
if ch==1:
insert_rec()
elif ch==2:
update_rec()
elif ch==3:
delete_rec()
elif ch==4:
view_rec()
elif ch==5:
break
else:
print("Wrong option selected")
3. Write a menu-driven program to store data into a MySQL database named shop and
table customer as following: