[go: up one dir, main page]

0% found this document useful (0 votes)
42 views84 pages

Prisha - Practical File

Practical file for different types of coding Mrs Divya parihar

Uploaded by

divyaofficial522
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views84 pages

Prisha - Practical File

Practical file for different types of coding Mrs Divya parihar

Uploaded by

divyaofficial522
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 84

ST.

XAVIER’S HIGH SCHOOL , VAPI


COMPUTER SCIENCE PRACTICAL 2023-24

BY PRISHA MATHUR
12-SCIENCE
TAUGHT BY- MS.SHAGUFA KHAN
ST.XAVIER’S HIGH SCHOOL,VAPI
COMPUTER SCIENCE (083)
PRACTICAL LIST 2023-24

SR.NO PRACTICAL NAME DATE T-SIGN


1. Write a program that receives two
numbers in a function and returns the
results of all arithmetic operations (+,-
,*,/,%)
2. Write a program that reads a text file
line by line and displays each word
separated by a #tag
3. Write a random number generator that
generates random number between 1 and 6
(stimulate a dice)
4. Write a program to remove all the lines
that contain character A in a file and write
it into another file
5. Write a program to get roll no , name and
marks of the students of a class and store
these details in a file called marks.txt
6. Write a program to read a text file and
display the count of vowels and
consonants in the file
7. 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.
8. Write a program to open file student.dat
and search for records with roll no as 12 or
14. If found, display the record.
9. Write a program to open a file student.dat
and display record having marks greater
than 81.
10. Write a program to create a binary file
with name ,roll no, marks. Input your roll
no and update the marks.
11. 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
12. 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
13. Write a program to create a csv file by
suppressing the end of line translation
14. Write a program to read and display the
content of employee.csv
15. Write a program to create a csv file by
entering user id and password , read and
search the password for given user id.

16. Write a program to implement a stack


using a list data structure.
17. Write a function push(student) and
pop(student) to add a new student name
and remove a student name from a list
student, considering them to act as PUSH
and POP operation of Data structure in
Python.
18. Write a menu based program to add, delete
and display the record of the hostel using a
list as a stack data structure in python.
Record of the hostel contains the fields:
Hostel number, Total students and
Total rooms.
19. Write SQL queries for (i) to (iv), which
are based on the table : STUDENT given
in the question:
(i) To display the records from
table students in
alphabetical order as per the
name of the student.
(ii) To display Class, Dob and City
whose marks are between 500
and 550.
(iii) To display Name, Class and
total number of students
who have secured more than
450 marks, class wise.
(iv) To increase marks of all
students by 20 whose class
is “XII”.
20. Write SQL commands for (a) to (f) from
table Students:
(a) To show all information about
the students of the History
department.
(b) To list the names of female
students who are in the Hindi
21. Given the following tables for a database
Library:
(a) To show Book name, Author
name and Price of books of
First Publ. publisher.
(b) To list the names from books
of Text type.
(c) To display the names and price
from books in ascending order of
their price.
(d) To increase the price of all books
of EPB Publishers by 50.
(e) To display the Book_Id,
Book_Name and
Quantity_Issued for all books
which have been issued.
(f) To insert a new row in the table
Issued having the following data :
“F0003”,1.
22. Consider the following Dept and Worker
tables. Write SQL queries for (i) to (iv) :
(i) To display wno, name, gender
from the table worker in
descending order of wno.
(ii) To display the name of all the
Female workers from the
table Worker.
(iii) To display the wno and name
of those workers from the
table Worker are born between
‘1987-01-01’ and ‘1991-12-
01’.
(iv) To count and display Male
workers who have joined after
‘1986-01-01’.
23. Write SQL commands for (a) to (c) from
table Students :
(a) Update marks of rollno. 2.

(b) Arrange the marks in


ascending order.
(c) Drop rollno. 5.

24. Write a python program that displays the


first three rows fetched from the
students table of MySQL database
Test(user :
“learner” and password : “fast”)
25. Write a query to fetch all rows from the
table book (Database : tests).
P1) Write a program that receives two numbers in a function and
returns the results of all arithmetic operations (+,-,*,/,%)

INPUT
def arcalc(x,y):
return x+y,x-y,x*y,x/y,x%y

num1=int(input("Enter number 1:"))


num2=int(input("Enter number 2:"))
add,sub,mult,div,mod=arcalc(num1,num2)
print("Sum of given numbers:",add)
print("Subtraction of given numbers:",sub)
print("Multiplication of given numbers:",mult)
print("Divison of given numbers:",div)
print("Modulo of given numbers:",mod)

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

THE CONTENTS IN prisha.txt BEFORE RUNNING THE CODE

THE FILE CONTAINING NAMES WITHOUT “a” IN IT

THE FILE CONTAINING NAMES WITH “a” IN IT


P5) Write a program to get roll no, name and marks of the students of a
class and store these details in a file called marks.txt

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

WHEN THE USER ENTERS CHOICE “1”


WHEN THE USER ENTERS CHOICE “2”

WHEN THE USER ENTERS CHOICE “3”


CSV FILE
P16) Write a program to implement a stack using a list data structure.

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")

ch=int(input("Enter your choice:"))

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

When the user enters choice “1”


When the user enters choice “2”

When the user enters choice “3”


When the user enters choice “4”
P17) Write a function push(student) and pop(student) to add a new
student name and remove a student name from a list student,
considering them to act as PUSH and POP operation of Data structure in
Python.

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

WHEN THE USER ENTERS CHOICE “1”

WHEN THE USER ENTERS CHOICE “2”


WHEN THE USER ENTERS CHOICE “3”
P18) Write a menu based program to add, delete and display the record
of the hostel using a list as a stack data structure in python. Record of
the hostel contains the fields: Hostel number, Total students and Total
rooms.

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])

while (ch=='y' or ch=='Y'):


print("1.Add Record")
print("2.Delete Record")
print("3.Display Record")
print("4.Exit")

op=int(input("Enter the choice:"))

if op==1:
push(host)
elif op==2:
pop(host)
elif op==3:
display(host)
elif op==4:
print("Exited!")
break

ch=input("Do you want to enter more records(y/n)? :")


SPYDER OUTPUT

WHEN THE USER ENTERS CHOICE “1”

WHEN THE USER ENTERS CHOICE “2”


WHEN THE USER ENTERS CHOICE “3”

WHEN THE USER ENTERS CHOICE “4”


P19) Write SQL queries for (i) to (iv), which are based on the table :
STUDENT given in the question:

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

(iv) To increase the marks of all students by 20 whose class is “XII”.

INPUT
update Student
set marks=marks+20
where class=’XII’;
OUTPUT
P20) Write SQL commands for (a) to (f) from table Students:

Table Students

(a) To show all information about the students of the History


department.

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

(c) To list names of all students with their date of admission in


ascending order.

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

(e) To display the information of number of students with Age<23.

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

(b) To list the names from books of Text type.

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

(d) To increase the price of all books of EPB Publishers by 50.

INPUT
update books
set price=price+50
where publisher=”EPB”;
OUTPUT

(e) To display the book_id, book_name and quantity_issued for all


books which have been issued.

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

(a) Update marks of rollno 2.

INPUT
update students
set marks=marks+10
where rollno=2;
OUTPUT

(b) Arrange the marks in ascending order.

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")

To create table student


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("create table Student(rollno int primary key,sname varchar(40) not


null,marks int,grade varchar(5),section varchar(5),project varchar(20))")
print("Table Student created")

To input values in student


table import mysql.connector as
sq1 conn=sq1.connect(
host="localhost",
user="learner",
password="fast",
database="Test")
if conn.is_connected():
print("Succesfully connected")

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:")

query="insert into student(rollno,sname,marks,grade,section,project)


values({},'{}',{},'{}','{}','{}')".format(rollno,name,marks,grade,section,project)
c1.execute(query)

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

print("Total number of rows:",count)

for row in data:


print(row)

conn.close()

OUTPUT

When the user creates the database

When the user creates the table


When the user inputs values

When the user fetches 3 rows

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")

To create table book


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("create table book(Title varchar(40) not null,ISBN varchar(40) primary
key)")

print("Table book created")


To insert values in table book
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()

for i in range(4):
t=input("Enter Title:")
i=input("Enter ISBN:")

query="insert into book(Title,ISBN) values('{}','{}')".format(t,i)


c1.execute(query)

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()

while row is not None:


print(row)
row=c1.fetchone()
OUTPUT

When the user creates database tests

When the user creates table book

When the user input data in table book


When the user fetches rows

MySQL output

You might also like