Class XII CS Practical File
Class XII CS Practical File
4 Create a binary file with name and roll number. Search for
a given roll number and display the name, if not found
display appropriate message.
Source code:
a=open(r"C:\Users\HP\Desktop\Hello World.txt","r")
lines=a.readlines()
for line in lines:
x=line.split()
for y in x:
print(y+" # ",end=" ")
print(" ")
Output:
2. Write a Python program to read a text file and display the number of vowels/ consonants/
uppercase/ lowercase characters in the file.
Source Code:
def cnt():
f=open(r"C:\Users\HP\Desktop\2.txt","r")
cont=f.read()
print(cnt)
v=0
cons=0
lc=0
uc=0
for ch in cont:
if (ch.islower()):
lc+=1
elif(ch.isupper()):
uc+=1
ch=ch.lower()
if( ch in ['a','e','i','o','u']):
v+=1
elif (ch in ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']):
cons+=1
f.close()
print("Vowels are : ",v)
print("consonants are : ",cons)
print("Lower case letters are : ",lc)
print("Upper case letters are : ",uc)
cnt()
Output:
3. Write a python program to remove all the lines that contain the character `a’ in a file and
write it to another file.
Source Code:
file=open(r"C:\Users\HP\Desktop\book.txt","r")
lines=file.readlines()
file.close()
file=open(r"C:\Users\HP\Desktop\book.txt","w")
file1=open(r"C:\Users\HP\Desktop\copy.txt","w")
for line in lines:
if 'a' in line:
file1.write(line)
else:
file.write(line)
print("Lines that contain a character are removed from book")
print("Lines that contain a character are added in copy")
file.close()
file1.close()
Output:
4. Create a binary file with name and roll number. Search for a given roll number and display
the name, if not found display appropriate message.
Source Code:
import pickle
sdata={}
slist=[]
totals=int(input("Enter no.of students:"))
for i in range(totals):
sdata["Roll no."]=int(input("enter roll no.:"))
sdata["Name"]=input("Enter name:")
slist.append(sdata)
sdata={}
a=open(r"C:\Users\HP\Desktop\text.dat","wb")
pickle.dump(slist,a)
a.close()
x=open(r"C:\Users\HP\Desktop\text.dat","rb")
slist=pickle.load(x)
b=int(input("Enter the roll number of student to be searched:"))
y=False
for text in slist:
if(text["Roll no."]==b):
y=True
print(text["Name"],"Found in file")
if(y==False):
print("Data of student not found")
Output:
5.Write a Python Program to Create a binary file with Empno, Name, Salary, then read and
display their details on screen
Source Code:
import pickle
def Write():
F=open("Emp.dat",'ab')
D={}
n=int(input("Enter how many employee details you want to store:"))
for i in range(n):
D['emp no']=int(input("Enter the employee number:"))
D['emp name']=input("Enter the employee name:")
D['Salary']=int(input("Enter the employee salary:"))
pickle.dump(D,F)
F.close()
def Read():
F=open("Emp.dat",'rb')
try:
while True:
s=pickle.load(F)
print(s)
except:
F.close()
Write()
Read()
Output:
6. Take a sample text file and find the most commonly occurring word. Also, list the
frequencies of words in the text file.
Source Code:
with open(r"C:\Users\HP\Desktop\text1.txt",'r') as fh:
contents=fh.read()
wordlist=contents.split()
wordfreq=[]
high=0
word=''
existing=[]
for w in wordlist:
wcount=wordlist.count(w)
if w not in existing:
wordfreq.append([w,wcount])
existing.append(w)
if wcount>high:
high=wcount
word=w
print("The word'"+word+"' occurs maximum number of times,",high,"times.")
print("\n other words have these frequencies:")
print(wordfreq)
Output:
7. Create a binary file with roll number, name and marks. Input a roll number and update the
marks.
Source code:
import pickle
sdata={}
totals=int(input("Enter the no.of students"))
a=open(r"C:\Users\HP\Desktop\text1.dat","wb")
for i in range(totals):
sdata["Roll no"]=int(input("Enter roll no:"))
sdata["Name"]=input("Enter name:")
sdata["Marks"]=float(input("Enter marks:"))
pickle.dump(sdata,a)
sdata={}
a.close()
found=False
rollno=int(input("Enter roll no to update:"))
a=open(r"C:\Users\HP\Desktop\text1.dat","rb+")
try:
while True:
pos=a.tell()
sdata=pickle.load(a)
if(sdata["Roll no"]==rollno):
sdata["Marks"]=float(input("Enter new marks:"))
a.seek(pos)
pickle.dump(sdata,a)
found=True
except EOFError:
if found==False:
print("Roll number not found")
else:
print("Student marks updated successfully")
a.close()
Output:
8. Write a python program to create a random number generator that generates random
numbers between 1 and 6 (simulates a dice).
Source Code:
import random
import time
print("Press CTRL+C to stop the dice ")
play='y'
while play=='y':
try:
while True:
for i in range(10):
print()
n = random.randint(1,6)
print(n,end='')
time.sleep(.00001)
except KeyboardInterrupt:
print("Your Number is :",n)
ans=input("Play More? (Y) :")
if ans.lower()!='y':
play='n'
break
Output:
9. Program to take 10 sample phishing email, and find the most common word occurring
Source code:
phishingemail=[
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
"[email protected]"
"[email protected]"
"[email protected]"
"[email protected]"
]
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 word is :",key_max)
Output:
10. Create a CSV file by entering user-id and password, read and search the password for given
user- id.
Source Code:
import csv
with open("7.csv", "w") as obj:
fileobj = csv.writer(obj)
fileobj.writerow(["User Id", "password"])
while(True):
user_id = input("enter id: ")
password = input("enter password: ")
record = [user_id, password]
fileobj.writerow(record)
x = input("press Y/y to continue and N/n to terminate the program\n")
if x in "Nn":
break
elif x in "Yy":
continue
with open("7.csv", "r") as obj2:
fileobj2 = csv.reader(obj2)
given = input("enter the user id to be searched\n")
for i in fileobj2:
next(fileobj2)
if i[0] == given:
print(i[1])
break
Output:
11. Create a python program to create and search students’ record in CSV file.
Source Code:
import csv
def Create():
F=open("Stu.csv",'a')
W=csv.writer(F)
opt='y'
while opt=='y':
No=int(input("Enter the student roll number:"))
Name=input("Enter the student name:")
Age=int(input("Enter the student age:"))
L=[No,Name,Age]
W.writerow(L)
opt=input("Do you want to add another student detail?(y/n):")
F.close()
def Read():
F=open("Stu.csv",'r',newline='\r\n')
no=int(input("Enter student roll number to search:"))
found=0
row=csv.reader(F)
for data in row:
if data[0]==str(no):
print("Student details are:")
print("=============================")
print("Name:",data[1])
print("Age:",data[2])
print("=============================")
found=1
break
if found==0:
print("The student roll number is not found")
F.close()
Create()
Read()
Output:
12. Write a program to create a CSV file with empid, name and mobile no. and search empid,
update the record and display the records.
Source code:
import csv
with open(r'C:\Users\HP\Desktop\employee.txt','a') as csvfile:
mywriter=csv.writer(csvfile,delimiter=',')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter employee ID:"))
name=input("Enter employee name:")
mobno=int(input("Enter employee mobile no:"))
mywriter.writerow([eno,name,mobno])
ans=input("Do you want to enter more data? (y/n):")
ans='y'
Output:
13. Write a Python program to implement a stack using list (PUSH & POP Operation on Stack).
Source code:
def isEmpty(s):
if len(s)==0:
return True
else:
return False
def push(s,item):
s.append(item)
top=len(s)-1
def pop(s):
if isEmpty(s):
return 'Underflow occurs'
else:
val=s.pop()
if len(s)==0:
top=None
else:
top=len(s)-1
return val
def peek(s):
if isEmpty(s):
return 'Underflow occurs'
else:
top=len(s)-1
return s[top]
def show(s):
if isEmpty(s):
print('no item found')
else:
t=len(s)-1
print('(TOP)',end='')
while(t>=0):
print(s[t],'<==',end='')
t=t-1
print()
s=[]
top=None
while True:
print('****** STACK IMPLEMENTATION USING LIST ******')
print('1: PUSH')
print('2: POP')
print('3: PEEK')
print('4: Show')
print('0: Exit')
ch=int(input('Enter choice:'))
if ch==1:
val=int(input('Enter no to push:'))
push(s,val)
elif ch==2:
val=pop(s)
if val=='Underflow':
print('Stack is empty')
else:
print('\nDeleted item is:',val)
elif ch==3:
val=peek(s)
if val=='Underflow':
print('Stack is empty')
else:
print('\nTop item is:',val)
elif ch==4:
show(s)
elif ch==0:
print('Bye')
break
Output:
14. Write a python program using function PUSH(Arr), where Arr is a list of numbers. From
this list push all numbers divisible by 5 into a stack implemented by using a list. Display the
stack if it has at least one element, otherwise display appropriate error message.
Source Code:
def isEmpty(Arr):
if len(Arr)==0:
return True
else:
return False
def push(Arr,item):
if item%5==0:
Arr.append(item)
top=len(Arr)-1
def show(Arr):
if isEmpty(Arr):
print('No item found')
else:
t=len(Arr)-1
print('(TOP)',end='')
while(t>=0):
print(Arr[t],'<==',end='')
t=t-1
print()
Arr=[]
top=None
while True:
print('****** STACK IMPLEMENTATION USING LIST ******')
print('1: PUSH')
print('2: Show')
print('0: Exit')
ch=int(input('Enter choice:'))
if ch==1:
val=int(input('Enter no to push:'))
push(Arr,val)
elif ch==2:
show(Arr)
elif ch==0:
print('Bye')
break
Output:
15. Write a python program using function POP(Arr), where Arr is a stack implemented by a
list of numbers and the function should return the value deleted from the stack.
Source code:
def isEmpty(Arr):
if len(Arr)==0:
return True
else:
return False
def push(Arr,item):
Arr.append(item)
top=len(Arr)-1
def pop(Arr):
if isEmpty(Arr):
return 'Underflow occurs'
else:
val=Arr.pop()
if len(Arr)==0:
top=None
else:
top=len(Arr)-1
return val
def show(Arr):
if isEmpty(Arr):
print('no item found')
else:
t=len(Arr)-1
print('(TOP)',end='')
while(t>=0):
print(Arr[t],'<==',end='')
t=t-1
print()
Arr=[]
top=None
while True:
print('****** STACK IMPLEMENTATION USING LIST ******')
print('1: PUSH')
print('2: POP')
print('3: Show')
print('0: Exit')
ch=int(input('Enter choice:'))
if ch==1:
val=int(input('Enter no to push:'))
push(Arr,val)
elif ch==2:
val=pop(Arr)
if val=='Underflow':
print('Stack is empty')
else:
print('\nDeleted item is:',val)
elif ch==3:
show(Arr)
elif ch==0:
print('Bye')
break
Output:
16. Write SQL queries for the following set of questions
Database: School
a) Write the query to create the above table and set the constraints for the attributes.
EXAMNO-PRIMARY KEY, NAME- NOT NULL ,MARK CHECK-MARK SHOULD NOT
EXCEED 500.
Query:
CREATE TABLE STUDENTS(
EXAMNO INT PRIMARY KEY,
NAME CHAR(20) NOT NULL,
CLASS VARCHAR(3),
SEC VARCHAR(3),
MARK INT CHECK(MARK<=500));
OUTPUT:
b) Write the query to insert the mentioned records into the table.
Query:
INSERT INTO STUDENTS VALUES (1201,'PAVINDHAN','XII','A1',489);
INSERT INTO STUDENTS VALUES (1202,'ESHWAR','XII','A1',465);
INSERT INTO STUDENTS VALUES (1203,'BHARKAVI','XII','A2',498);
INSERT INTO STUDENTS VALUES (1204,'HARIPRIYA','XII','A2',400);
INSERT INTO STUDENTS VALUES(1205,'JAIPRADHAP','XII',NULL,398);
INSERT INTO STUDENTS VALUES(1206,'KAVIPRIYA','XII','A2',NULL);
c) Write the query to display all the student records who is
studying in A1 SECTION.
QUERY:
SELECT * FROM STUDENTS WHERE SEC='A1';
d) Write the query to display the records whose mark is not assigned.
QUERY:
SELECT * FROM STUDENTS WHERE MARK IS NULL;
e) Write the query to display whose marks in the range 400 to 450 (both values are
inclusive).
QUERY:
SELECT * FROM STUDENTS WHERE MARK BETWEEN 400 AND 450;
OUTPUT:
17. Write SQL queries for the following set of questions
DATABASE: HOSPITAL
a) Write the query to create DOCTOR TABLE and the PATIENT TABLE and keep
DOCID in patient table to be the foreign key .
QUERY:
CREATE DATABASE HOSPITAL;
USE HOSPITAL;
b) Write the query to display the count of male and female patients in the age between 40
and 50.
QUERY:
SELECT GENDER,COUNT(GENDER) FROM PATIENT WHERE AGE BETWEEN 40 AND 50
GROUP BY GENDER;
c) Write the query to display the patient id,name and age who fixed the appointment on
September month.
QUERY:
SELECT PATID,PNAME,AGE FROM PATIENT WHERE MONTH(APMDATE)=09;
QUERY:
SELECT DEPT,COUNT(DOCID) FROM DOCTOR GROUP BY DEPT;
e) Write the query to display the sum of the salary of the doctors department wise.
QUERY:
SELECT DEPT,SUM(SALARY) FROM DOCTOR GROUP BY DEPT;
OUTPUT:
18. Write a python program to create the table and insert the records into the table by getting
the data from the user and to store in the MySQL database.
DATABASE : MYSCHOOL
TABLE NAME : STUDENT
ATTRIBUTES : EXAMNO,NAME,CLASS,SECTION,MARK
PROGRAM:
import mysql.connector as mycon
a=mycon.connect(host='localhost',user='root',password='Password@123',database='MYSCHOOL')
if a.is_connected():
print("Database connected")
else:
print("Database not connected")
b=a.cursor()
q1="drop table if exists student"
b.execute(q1)
q="create table student(EXAMNO INT NOT NULL PRIMARY KEY,NAME
VARCHAR(20),CLASS INT,SECTION VARCHAR(2),MARK INT)"
b.execute(q)
ans='y'
while ans.lower()=='y':
ex=int(input("ENTER EXAMNO:"))
na=input("ENTER NAME:")
cl=int(input("ENTER CLASS:"))
s=input("ENTER SECTION:")
m=int(input("ENTER MARK:"))
q2="insert into student values({},'{}',{},'{}',{})".format(ex,na,cl,s,m)
b.execute(q2)
print("Record successfully stored in the student table")
ans=input("Do you want to add another record(y/n):")
a.commit()
a.close()
OUTPUT:
19. Write a python program to search the records from the table based on the examno and
display the details of the student.
DATABASE : MYSCHOOL
TABLE NAME : STUDENT
PROGRAM:
import mysql.connector as mycon
fh=mycon.connect(host='localhost',user='root',password='Password@123',database='MYSCHOOL')
if fh.is_connected():
print("Database connected")
else:
print("Database not connected")
ans='y'
while ans.lower()=='y':
a=fh.cursor()
r=int(input("ENTER THE EXAMNO YOU WANT TO SEARCH:"))
q1="select * from student where examno={}".format(r)
a.execute(q1)
rec=a.fetchall()
cnt=a.rowcount
if cnt!=0:
for i in rec:
print('EXAM NO:',i[0])
print('NAME :',i[1])
print('CLASS :',i[2])
print('SECTION :',i[3])
print('MARKS :',i[4])
else:
print('RECORD NOT FOUND')
ans=input('DO YOU WANT TO SEARCH ANOTHER RECORD (Y/N):')
fh.close()
OUTPUT:
20. Write a program to Integrate SQL with Python by importing the MySQL module to search
a student using exam no update the mark.
PROGRAM:
import mysql.connector as mycon
fh=mycon.connect(host='localhost',user='root',password='Password@123',database='MYSCHOOL')
if fh.is_connected():
print("Database connected")
else:
print("Database not connected")
a=fh.cursor()
examno=int(input("Enter exam number:"))
mark=int(input("Enter new mark:"))
fh.close()
OUTPUT