Prisha - Practical File
Prisha - Practical File
BY PRISHA MATHUR
12-SCIENCE
TAUGHT BY- MS.SHAGUFA KHAN
ST.XAVIER’S HIGH SCHOOL,VAPI
COMPUTER SCIENCE (083)
PRACTICAL LIST 2023-24
INPUT
def arcalc(x,y):
return x+y,x-y,x*y,x/y,x%y
SPYDER OUTPUT
P2) Write a program that reads a text file line by line and displays each
word separated by a #tag.
INPUT
def wordseparated():
myfile=open("Python.txt","r")
lines=myfile.readlines()
for line in lines:
words=line.split()
for word in words:
print(word+"#",end=" ")
print()
myfile.close()
wordseparated()
OUTPUT
TEXT FILE
SPYDER OUTPUT
P3) Write a Random number generator that generates random number
between 1 and 6 (Stimulate a Dice).
INPUT
import random
while True:
print("="*20)
print("***ROLLING THE DICE***")
print("="*20)
num=random.randint(1,6)
print(num)
ch=input("Roll Again?(Y/N)")
if ch in "Nn":
break
print("Thanks for playing!!!")
SPYDER OUTPUT
P4) Write a program to remove all the lines that contain character A in a
file and write it into another file.
INPUT
fileout=open("prisha.txt","r")
fn=open("prisha3.txt","w")
f1=open("prisha2.txt","w")
lines=fileout.readlines()
for line in lines:
if "a" in line:
fn.write(line)
for line in lines:
if not "a" in line:
f1.write(line)
fileout.close()
fn.close()
OUTPUT
INPUT
count=int(input("How many students?"))
fileout=open("marks.txt",'w')
for i in range(count):
print("Enter details of students:")
roll=int(input("roll no:"))
name=input("name:")
marks=float(input("marks:")) rec=str(roll)
+","+name+","+str(marks)+"\n"
fileout.write(rec)
fileout.close()
OUTPUT
SPYDER OUTPUT
TEXT FILE
P6) Write a program to read a text file and display the count of vowels
and consonants in the file.
INPUT
myfile=open("answer.txt",'r')
ch=" "
vcount=0
ccount=0
while ch:
ch=myfile.read(1)
if ch in["a","A","e","E","I","i","O","o","U","u"]:
vcount=vcount+1
else:
ccount=ccount+1
print(vcount)
print(ccount)
myfile.close()
OUTPUT
SPYDER OUTPUT
TEXT FILE
P7) Write a program to get roll no, name and marks of the students of a
class and write onto a binary file. The program should be able to get
data from the user and write onto the file as long as the user wants.
INPUT
import pickle
stu={}
stufile=open("stu.dat","wb")
ans="y"
while ans=="y":
rno=int(input("Enter roll no:"))
name=input("enter name:")
marks=float(input("Enter marks:"))
stu["Rollno"]=rno
stu["Name"]=name
stu["Marks"]=marks
pickle.dump(stu,stufile)
ans=input("Want to enter more records(y/n)?")
stufile.close()
OUTPUT
SPYDER OUTPUT
BINARY FILE
P8) Write a program to open file student.dat and search for records
with roll no as 12 or 14. If found, display the record.
INPUT
import pickle
fin=open("stu.dat","rb")
searchkeys=[12,14]
try:
print("Searching on file stu.dat ..")
while True:
stu=pickle.load(fin)
if stu["rollno"] in searchkeys:
print(stu)
found=True
except EOFError:
if found==False:
print("No such records found in file.")
else:
print("Search succesful.")
fin.close()
OUTPUT
SPYDER OUTPUT
BINARY FILE
P9) Write a program to open a file student.dat and display record
having marks greater than 81.
INPUT
import pickle
stu={}
found=False
fin=open("student.dat","rb")
print("Searching in file stu.dat..")
try:
while True:
stu=pickle.load(fin)
if stu["Marks"]>81:
print(stu)
found=True
except EOFError:
fin.close()
if found==False:
print("No such records with Marks>81")
else:
print("Search successful.")
SPYDER OUTPUT
BINARY FILE
P10) Write a program to create a binary file with name, roll no, marks.
Input your roll no and update the marks.
INPUT
import pickle
studentdata={}
students=int(input("How many students?"))
myfile=open("ss.dat","wb")
for i in range(students):
studentdata['Rollno']=int(input("Enter roll no.:"))
studentdata['Name']=input("Enter name:")
studentdata['Marks']=float(input("Enter marks:"))
pickle.dump(studentdata,myfile)
studentdata={}
myfile.close()
import pickle
studentdata={}
found=0
rollno=int(input("Enter roll no. to search:"))
myfile=open("ss.dat","rb+")
try:
while True:
pos=myfile.tell()
studentdata=pickle.load(myfile)
if(studentdata['Rollno'])==rollno:
studentdata['Marks']=float(input("Enter marks to update:"))
myfile.seek(pos)
pickle.dump(studentdata,myfile)
found=1
except EOFError:
if (found==0) :
print("Roll no not found,please try again")
else:
print("Syudent marks updated succesfully")
myfile.close()
import pickle
studentdata={}
myfile =open("ss.dat","rb")
try:
while True:
studentdata=pickle.load(myfile)
print(studentdata)
except EOFError:
myfile.close()
SPYDER OUTPUT
BINARY FILE
P11) Write a program to open a file student.dat and add additional
bonus marks of 2 to those students whose marks is greater than 81.
INPUT
import pickle
stu={}
found=False
fin=open("stu.dat","rb+")
try:
while True:
rpos=fin.tell()
stu=pickle.load(fin)
if stu["Marks"]>81:
stu["Marks"]+=2
fin.seek(rpos)
pickle.dump(stu,fin)
found=True
except EOFError:
if found==False:
print('Sorry,no matching record found.')
else:
print("Record(s) succesfully updated.")
fin.close()
SPYDER OUTPUT
BINARY FILE
P12) Write a program to create a csv file to store student data (roll no,
name, marks). Obtain data from user and write 5 records into the file.
INPUT
import csv
fh=open("student.csv","w")
stuwriter=csv.writer(fh)
stuwriter.writerow(["Rollno","Name","Marks"])
sturec=[]
for i in range(5):
print("Student record",(i+1))
rollno=int(input("Enter rollno:"))
name=input("Enter name:")
marks=float(input("Enter marks:"))
sturec=[rollno,name,marks]
stuwriter.writerow(sturec)
fh.close()
OUTPUT
SPYDER OUTPUT
CSV FILE
P13) Write a program to create a csv file by suppressing the end of line
translation.
INPUT
import csv
fh=open("Employee.csv","w",newline ='')
ewriter=csv.writer(fh)
empdata=[ ["Empno","Name","Designation","
Salary"],
[1001,"Trupti","Manager",56000],
[1002,"Prisha","Manager",55900],
[1003,"Simran","Analyst",35000],
[1004,"Silviya","Clerk",25000],
[1002,"Suji","PR Officer",31000],
]
ewriter.writerows(empdata)
print("File succesfully created")
fh.close()
OUTPUT
SPYDER OUTPUT
CSV FILE
P14) Write a program to read and display the content of employee.csv
INPUT
import csv
with open("Employee.csv","r") as fh:
ereader=csv.reader(fh)
print("File Employee.csv contains:")
for rec in ereader:
print(rec)
SPYDER OUTPUT
CSV File
P15) Write a program to create a csv file by entering user id and
password, read and search the password for given user id.
INPUT
import csv
def write():
f=open("prisha.csv","w")
wo=csv.writer(f)
wo.writerow(['UserID','Password'])
while True:
u_id=input("Enter UserID:")
pswd=input("Enter password:")
data=[u_id,pswd]
wo.writerow(data)
ch=input("Do you want to enter more records(y/n):")
if ch in "Nn":
break
def read():
f=open("prisha.csv","r")
ro=csv.reader(f)
for i in ro:
print(i)
def search():
with open("prisha.csv","r") as obj2:
fileobj2=csv.reader(obj2)
U=input("Enter UserID:")
for i in fileobj2:
next(fileobj2)
#print(i,given)
if i[0]==U:
print("Password:",i[1])
break
obj2.close()
print("Select operation")
print("1.Write")
print("2.Read")
print("3.Search")
ch=int(input("Enter choice:"))
if ch==1:
write()
elif
ch==2:
read()
elif ch==3:
search()
else:
print("Choose correct operation")
SPYDER OUTPUT
INPUT
def push(stk,elt):
stk.append(elt)
print("Element inserted")
print(stk)
def isempty(stk):
if stk==[]:
return True
else:
return False
def pop(stk):
if isempty(stk):
print("Stack is empty")
else:
print("Deleted element is:",stk.pop())
def peek(stk):
if isempty(stk):
print("Stack is empty")
else:
print("Element at the top of the stack:",stk[-1])
def
display(stk):
a=stk[::-1]
print(a)
stack=[]
while True:
print("Stack operation")
print("1.Push")
print("2.Pop")
print("3.Peek")
print("4.Display")
print("5.Exit")
if ch==1:
element=int(input("Enter the element:"))
push(stack,element)
elif ch==2:
pop(stack)
elif ch==3:
peek(stack)
elif ch==4:
display(stack)
elif ch==5:
break
OUTPUT
INPUT
sk=[]
def push(sk):
sn=input("Enter student name:")
sk.append(sn)
def pop(sk):
if(sk)==[]:
print("Stack is empty")
else:
print("Deleted student name :",sk.pop())
while True:
a=print("1.Push \n2.Pop \n3.Exit:")
i=int(input("Enter your choice:"))
if i==1:
push(sk)
elif i==2:
pop(sk)
elif i==3:
print("Exit!!")
OUTPUT
INPUT
host=[]
ch='y'
def push(host):
h=int(input("Enter Hostel Number:"))
t=int(input("Enter Total Students:"))
r=int(input("Enter Total Rooms:"))
temp=[h,t,r]
host.append(temp)
def pop(host):
if (host==[]):
print("Stack is empty!")
else:
print("Deleted Record is:",host.pop())
def display(host):
l=len(host)
print("Hostel Number\t Total Students\t Total Rooms")
for i in range(l-1,-1,-1):
print(host[i][0],"\t\t\t\t",host[i][1],"\t\t\t\t",host[i][2])
if op==1:
push(host)
elif op==2:
pop(host)
elif op==3:
display(host)
elif op==4:
print("Exited!")
break
Table Student
(i) To display the records from table Student in alphabetical order as per
the name of the student.
INPUT
select *
from Student
order by name;
OUTPUT
(ii) To display class, dob and city whose marks are between 500 and
550.
INPUT
select class,dob,city
from Student
where marks between 500 and 550;
OUTPUT
(iii) To display name, class and total number of students who have
secured more than 450 marks, class wise.
INPUT
select name,class,count(*)
from Student
where marks>450
group by class;
OUTPUT
INPUT
update Student
set marks=marks+20
where class=’XII’;
OUTPUT
P20) Write SQL commands for (a) to (f) from table Students:
Table Students
INPUT
select *
from Students
where Department=”History”;
OUTPUT
(b) To list the names of female students who are in the Hindi
department.
INPUT
select *
from Students
where Sex=”F” and Department=”Hindi”;
OUTPUT
INPUT
select name
from Students
order by Date_of_adm;
OUTPUT
(d) To display a student’s name, fee, age for male students only.
INPUT
select Name,Fee,Age
from Students
where Sex=’M’;
OUTPUT
INPUT
select *
from Students
where Age<23;
OUTPUT
(f) To insert a new row in the Student table with the following data :
9,”Zaheer”,36,”Computer”,[1997-03-12],230,”M”.
INPUT
insert into Students values(9,’Zaheer’,36,’Computer’,’1997-03- 12’,230,’M’);
OUTPUT
P21) Given the following tables for a database Library:
Table Books
Table Issued
(a) To show book name, author name and price of books of First Publ.
publisher.
INPUT
select book_name,author_name,price
from books
where publisher=”First Publ” ;
OUTPUT
INPUT
select book_name
from books
where type=”Text”;
OUTPUT
(c) To display the names and price from books in ascending order of
their price.
INPUT
select book_name,price
from books
order by price;
OUTPUT
INPUT
update books
set price=price+50
where publisher=”EPB”;
OUTPUT
INPUT
select books.book_id,book_name,quantity_issued
from books,issued
where books.book_id=issued.book_id;
OUTPUT
(f) To insert a new row in the table issued having the following data :
“”F0003”,1 .
INPUT
Insert into issued
Values(‘’F003’’,1);
OUTPUT
P22) Consider the following Dept and Worker tables. Write SQL queries
for (i) to (iv):
Table Dept
Table Worker
(i) To display wno, name, gender from the table Worker in descending
order of wno.
INPUT
select wno,name,gender
from Worker
order by wno desc;
OUTPUT
(ii) To display the name of all the Female workers from table Worker.
INPUT
select name
from Worker
where gender=”F”;
OUTPUT
(iii) To display the wno, name of those workers from the table Worker
who are born between ‘1987-01-01’ and ‘1991-12-01’.
INPUT
select wno,name
from Worker
where dob between “1987-01-01” and “1991-12-01”;
OUTPUT
(iv) To count and display Male workers who have joined after ‘1986-01-
01’.
INPUT
select count(*)
from Worker
where gender=’M’ and doj>’1986-01-01’;
OUTPUT
P23) Write SQL commands for (a) to (c) from table Students:
Table Students
INPUT
update students
set marks=marks+10
where rollno=2;
OUTPUT
INPUT
select *
from students
order by marks asc;
OUTPUT
(c) Drop rollno 5.
INPUT
delete from students
where rollno=5;
OUTPUT
P24) Write a python program that displays the first three rows fetched
from the students table of MySQL database Test (user:”learner” and
password:”fast”).
INPUT
To create database
import mysql.connector
mydb=mysql.connector.connect(
host="localhost",
user="learner",
password="fast")
mycursor=mydb.cursor()
mycursor.execute("create database Test")
print("Database Created")
c1=conn.cursor()
for i in range(5):
rollno=int(input("Enter student rollno:"))
name=input("Enter student name:")
marks=int(input("Enter student marks:"))
grade=input("Enter student grade:")
section=input("Enter student section:")
project=input("Enter student project:")
print("Values inserted")
conn.commit()
Main code
import mysql.connector as sq1
conn=sq1.connect( host="local
host", user="learner",
password="fast",
database="Test")
if conn.is_connected():
print("Succesfully connected")
c1=conn.cursor()
c1.execute("Select * from
Student")
data=c1.fetchmany(3)
count=c1.rowcount
conn.close()
OUTPUT
MySQL output
P25) Write a query to fetch all rows from the table book (Database :
tests).
INPUT
To create database tests
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",password="1234")
mycursor=mydb.cursor()
mycursor.execute("create database tests")
print("Database Created")
c1=conn.cursor()
c1.execute("create table book(Title varchar(40) not null,ISBN varchar(40) primary
key)")
c1=conn.cursor()
for i in range(4):
t=input("Enter Title:")
i=input("Enter ISBN:")
print("Values inserted")
conn.commit()
Main code
import mysql.connector as sq1
conn=sq1.connect(host="localhost",user="root",password="1234",database="test
s")
if conn.is_connected():
print("Succesfully connected")
c1=conn.cursor()
c1.execute("Select * from book")
row=c1.fetchone()
MySQL output