0 ratings0% found this document useful (0 votes) 47 views40 pagesComp Ultimate Prac
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
VIDYANTRIKSH
SR. SECONDARY
SCHOOL
NAME: PRIYANSHU
GRADE:12TH “SCIENCE”
COMPUTER SCIENCE
PRACTICAL FILENo.
Practical name
Date
Signatu
re
Program to read. and display file content line by
line with each word separated by “#”
2 | Program to read the content of file and display the
total number of consonants, uppercase, vowels
and lowercase characters.
3. | Program to read the content of file line by line and
writevit to another file except for the lines
containing “a” letter in it.
4 | Program to create binary file to store roll number
and names, search any roll number display name
if roll number found otherwise “Roll number not
found”
5 Program to create binary file to restore Roll
number, name and marks and update marks of,
entered)Roll number.
6 Program to generate random number 1-6,
simulating a dice,
7 | Program to implementStack in python using List.
8 Creative CSVifile by entering/user-id and
password, read and search.the password for given
userdd.
9 | Consider the following MOVIE table andiwrite the
SQL queries based on it.
10 Write following queries!
11 | Consider the following matches, teams table and
write SQL queries based on it.
12 | Consider the following table and write the queries:
13 | Perform create database and Write a MySQL
connectivity program in python.
14 | Perform all the operations with reference to table
‘students through MySQL-Python Connectivity.PYTHON
PROGRAMs
PRACITCALProgram 1: Program to read and display file content line by
line with each
word separated by “ #”
OUTPUT
Hello#guys#my#name#
Is#abc#and#in#today's#
Video#we#are#playing#at
GameProgram 2: Program to read the content of file and display the
total number of
consonants, uppercase, vowels and lower case characters.
#Program to read content of file
#and display total number of vowels, consonants, lowercase and
uppercase characters
f = open("file1 txt")
v=0
c=0
u=0
=O
o=0
data = f.read(),
for ch in data:
if ch.isalpha():
if ch.lower() in vowels:
Vt+=1
else:
cre
if ch.isupper():
ut=1
elif ch.islower():
a1
elif ch!="' and ch!="\n':
ot=1
print("Total Vowels in file :",v)
print("Total Consonants in file :",c)
print("Total Capital letters in file :",u)
print("Total Small letters in file :",1)
print("Total Other than letters :",o)
f.close()NOTE : if the original content of file is:
Hello guys my name is
Xyz and we are playing Minecraft
Version 1@20
OUTPUT
Total Vowels in file.
Total Consonants in file n :Program 3: Program to read the content of a file line by line
and write it to another file except for the lines containing “a”
letter in it.
#Program to read line from file and write it to another line#Except
for those line which contains letter ‘a’
f1 = open("file2.txt")
2 = open("file2copy.txt"
for line in f1:
if ‘a’ nofin line:
2.write(line)
print(‘## File Copied Successfully! ##’),
f1.close()
f2.close()
NOTE: Content of file2.txt
Gta 6 is going to be
Launched in 2025
Two three four five
Hello guys welcome to the show!
OUTPUT
## File Copied Successfully! ##
NOTE: After copy content of file2copy.txt
Two three four five
Hello guys welcome to the show!Program 4: Program to create binary file to store Rollno and
Name, Searchany Rollno and display name if Rollno found
otherwise “Rollno not found”
import pickle
def write():
D=0
f=open(Studentdetails.dat","wb')
while True:
r= int(input ("Enter Roll no :"))
n= input(‘Enter Name")
D[Roll No'} = r
D['Name'] = n
pickle.dump(D;f)
ch = input("More ? (Y/N)")
if ch in ‘Nn’
break
f.close()
def Search() :
found = 0
rollno= int(input("Enter Roll no Whose name you want to display
")
f = open("Studentdetails.dat", "tb")
try:
while True:
rec = pickle.load(f)
if rec['Roll No']==rollno:
print(rec['Name'])
found = 1
break
except EOFError:
if found == 0:
print("Sorry not Found....")
f.close()write()
Search()
OUTPUT
Enter Roll no : 1
Enter Name : michael
More ? (Y/N)y
Enter Roll no: 2
Enter Roll no W
display :3
Franklin
Enter R
display
SortProgram 5: Program to create binary file to store Rollno, Name
and Marksand
update marks of entered Rollno.
#Program to create a binary file to store Rollno and name
#Search for Rollno and display record if found #otherwise
“Roll no. not found"
import pickle
def Write():
f = open("Studentdetails.dat", 'wb’)
while True:
m=int(input ("Enter Roll no : "))
n= input(Enter Name :")
m = int(input ("Enter Marks : "))
record= [r,n,m]
pickle.dump(record, f)
ch = input("Do you want.to‘enter,more ?(Y/N)")
if ch in ‘Nn’;
break
f.close()
def Read():
f = open("Studentdetails.dat"'rb')
try:
while True:
tec=pickle.load(f)
print(rec)
except EOFError:
f.close()
def Update():
f = open("Studentdetails.dat", 'rb+')rollno = int(input("Enter roll no whoes marks you want to
update");
try:
while True:
pos=f.tell()
rec = pickle.load(f)
‘ollno:
int(input("Entel
Enter Name : va
Enter Marks : 63
Do you want to enter more ?(Y/N)y
Enter Roll no : 2
Enter Name : henry
Enter Marks : 33
Do you want to enter more ?(Y/N)n
[1, ‘vaibhav', 63]
[2, 'henry', 33]
Enter roll no whose marks you want to update : 2
Enter Update Marks:76Program 6: Program to generate random number 1-6,
simulating a dice.
# Program to generate random number between 1 - 6# To
simulate the dice
import random
while True:
"*55)
en RES aling Dice enntentennnitatisesene
print("=""55)
num = random.randint(1\6)
if num ==6:
print(Hey.....You got",;num,"....... Congratulations!!!)
elif num ==1"
print("Well tried.... But you got",num)
else:
print("You got:",num)
ct put("Roll again? (Y/N)"),
if.chin "Nn":
break
steneneenananeneaneneeR ling Digetttinitntntnanintnnnaninnts
You got: 3
Roll again? (Y/N)y
Thanks for playing!
steneneeeeneeeeeeteR olling Digg tttnnenentnentnsetitiesYou got: 5
Roll again? (Y/N)nProgram 7: Write a program to implement a stack for the
employee details (empno,name).Code:
#stack implementation using functions
#program to create a stack of employee(empno,name,sal).
employee=[]
def push():
empno=input("Enter empno ")
name=input("Enter name ")
sal=input("Enter sal ")
emp=(empno,name,sal)
employee.append(emp)
def pop():
if(employee==[]):
print('Underflow/ Employee Stack in empty")
else:
empno,name,sal=employee.pop()
print("poped element is ")
print("empnoy",empno," name ",name," salary ",sal)
def traverse():
if not (employee==[)):
n=len(employee)
for i in range(n-1,-1,-1):
print(employee[i])
else:
print("Empty , No employee to display")
while True:
print("1. Push")
print("2. Pop")
print("3. Traversal")
print("4. Exit")
ch=int(input("Enter your choice "))
if(ch==1):
push()elif(ch==2):
pop()
elif(ch==3):
traverse()
elif(ch: f
print("End")
break
else:
4.Exit
Enter your choice 3
(14,'gautam’,‘70000’)
1.Push
2.Pop
3. Traversal
4.ExitProgram 8: Create a CSV file by entering user-id and
password, read and search the password for given user- id.
import csv
with open("7.csv", "w") as obj:
v.writer(obj)
fileobj.writerow(["User,
terminate
# print(i,given)
if i[0] == given:
print(i[1})
breakSQL
QUERIES
PRACTICALProgram 9: Consider the following MOVIE table and write the SQL queries
based on it.
Movie 1D) MovieName | Type ReleaseDate | ProductionCost | BusinessCost
™Moo1 Kashmir Files _| Action 2022/01/26 | 1245000 1300000
Moo2 ‘Attack Action 2022/01/28 | 1120000 1250000
‘M003 Loop Lapeta _| Thriller 2022/02/01 | 250000 300000
M004 Badhaiho | Drama 2022/02/04 | 720000 68000
MOOS ‘Shabashrae | Biography _| 2022/02/04 _| 1000000 ‘800000
M006 Gehraiyaan | Romance 2022/02/11 | 150000 120000
a) Display all information from movie.
b) Display the type of movies.
c) Display movie id, movie name, total_earning by showing the business
done by the movies. Calculate the business done by movie using the sum
of production cost and business cost.
d) Display movie id, movie name and production cost for all movies with
production cost greater that 150000 and less than 1000000.
e) Display the movie of type action and romance.
f)_ Display the movie of type action and romance.
ANSWER:
a) select * from movie;b) select distinct from a movie;
TS TESTE ES
c) select movieid, moviename, productioncost+businesscost”total earning”
from movie;
d) select movie_id, moviename, productioncost from movie where
productcost is >150000 and <1000000;
e) select moviename from movie where type='action’ or type="romance’;f) select moviename from movie where month(releasedate)=2;
> Lapeta
=r a)
eee ea)Program 10: Write following queries.
a) Write a query to display cube of 5.
b) Write a query to display the number 563.854741 rounding off to the next
hundred
C) Write a query to display "put" from the word "Computer".
d) Write a query to display today's date into DD.MMYYYY format.
€) Write a query to display 'DIA' from the word "MEDIA".
f) Write a query to display movie name - type from the table movie.
g) Write a query to display first four digits of production cost.
h) write a query to display last four digits of business cost.
i) Write a query to display weekday of release dates.
j) Write a query to display day name on which movies are going to be
released.
ANSWERS:
a) select pow(5,3);
ys
mid( "Computer" ,4,3)5
mid("Computer",
.
I
.
|
+c) select mid(“computer”,4,3);
d) select concat(day(now())), concat(“’,;month(now())),
concat((“’,year(now())))”Date”;
e) select right(“Media”,3);
select right( "Media" ,3);g) select left(productioncost,4) from movie;
lect left (productic
ft (productioncost,4)
rare : es
inesscost,4)
Sr Tse =) from movie;
weekday (releasedatProgram 11: Suppose your school management has decided to conduct
cr
icket 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:
A. Create a database “Sports”.
B. Create a table “TEAM” with following considerations:
a) It should have a column TeamID for storing an integer value between
1 to 9, which refers to unique identification of a team.
b) Each TeamID should have its associated name (TeamName), which
should be a string of length not less than 10 characters.
C) Using table level constraint, make TeamID as the primary key.
a) Show the structure of the table TEAM using a SQL statement.
b) As per the preferences of the students four teams were formed
as given below. Insertthese four ros in TEAM table:
a) Row 1: (1, Tehlka)
b) Row 2:(2, Toofan)
C) Row 3: (3, Aandhi)
d) Row 3: (4, Shailab)
d) Show the contents of the table TEAM using a DML statement.
e) Now create another table MATCH_DETAILS and insert data as shown
below:
MatchID | MatchDate | FirstTeamID | SecondTeamID | FirstTeamScore | STSc
M1 2021/12/20 2 107 93
M2 2021/12/21 | 3 a 156 158
M3. 2021/12/22 | 1 3 86 81
M4 2021/12/23 | 2 4 65 67
MS. 2021/12/24 | 1 4 52 88
M6 2021/12/25 | 2 3 97 68ANSWERS:
a) create database sports;
Dot E ee aot et totes
1 y OK, 1 row affected (@-01 sec
Eat use sports;
eee changed
b) creating table with the given specification:
create table team ->(teamid int(1), -> teamnamevarchar(10), primary
key(teamid));
¢) desc team;
Prt)
Field Ts ree Pears
Pst) int
teamname | varchar(10) | YES
i
I
i ime
| I
me: |
| |
(@.01 sec)
INSERTING DATA:
mysql -> Insert into team -> values(1/Tehlka’);
ene
ee ee
ed
eS ae
eae
oe
SS
row affectedSHOW THE CONTENT OF TABLE — TEAM:
select * from team;
Tehlka
Toofan
Aandhi
rows
CREATING ANOTHER TABLE:
Create table match_details
(matchid varchar(2) primary key, -> matchdate date, -> firstteamid int(1)
references team(teamid), -> secondteamid int(1 refrences team(teamid),
-> firstteamscore int(3), -> secondteamscore int(3));
create table match_details
rasa tt Me ai eS ee ticle Y>
sansa
firstteamid int(1) references team(teamid),
econdteamid int(1) references team(teamid),
ett ae cite eae
econdteamscore int(3));
@ rows affected, 4 warnings (0.03Program 12: Consider the following table and write the queries:
itemno item dcode qty unitprice _ | Stockdate
S005 Ballpen _| 102 100 10 2018/04/22
S003 GelPen | 101 150 15 2018/03/18
S002 Pencil 102 125 5 2018/02/25
S006 Eraser 101 200 3 2018/01/12
$001 Sharpner__| 103 210 5 2018/06/11
s004 Compass _| 102 60 35 2018/05/10
S009 A4Papers | 102 160 5 2018/07/17
a) Display all the items in the ascending order of stock date.
b) Display maximum price of items for each dealer individually as per dcode
from stock.
C) Display all the items in descending orders of item names.
) Display average price of items for each dealer individually as per dcode
from stock which average price is more than 5.
€) Display the sum of quantity for each dcode.
ANSWERS:
a) select * from stock order by stockdate;b) select dcode, max(unitprice) from stock group by code;
Ee er avery
) select dcode,avg(unitprice) from stock group by dcodehaving avg(unitprice)>5;
€) select dcode,sum(qty) from stock group by dcode;PYTHON
DATABASE
CONNECTIVITYProgram 13: Write a MySQL connectivity program in Python to:
© Create a database school
© Create a table students with the specifications - ROLLNO
integer, STNAME character(10) in MySQL and perform the
following operations:
© Insert two records in it
© Display the contents of the table
coDI
import mysq.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
port="3306",
#database="my_first_db"
)
def c_database():
try:
input("Enter Database Name
cexecute["create database {)".format(dn))
cexecute("use {}".format(dn))
print("Database created successfully")
except Exception as a:
print("Database Error”,a)
‘#Function to Drop Database as per users choice
def d_database():
try:
dn=input("Enter Database Name to be dropped=")
cexecute("drop database {}" format(dn))print("Database deleted sucessfully")
except Exception as a:
print("Database Drop Error”,a)
#Function to create Table
def c_table()
ty:
c.execute("create table students(rolino int(3),stname varchar(20));")
Hmycursor.execute("CREATE TABLE customers (name VARCHAR(255), address
VARCHAR(255))")
print("Table created successfully")
except Exception as a:
print("Create Table Error",a)
‘Function to Insert Data
def e_datal):
ty:
while True:
‘no=int(input("Enter student rolino="))
name=input("Enter student name="
cexecute("use {)".format('STD12'))
c.execute("insert into students values({},'{});".format(mo,name))
mydb.commit()
choice=input("Do you want to add more recor
if choice in "Nn":
break
except Exception as a:
print("Insert Record Error",a)
#Function to Display Data
def d_datal):
try:
cexecute("select * from students")
for {in data:print(i)
‘except Exception as a:
print("Display Record Error",a)
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root",
port="3306",
print("Wrong option selected")OUTPUT:
MENU
1. Create Database
2. Drop Database
3.Create Table
Ansert Record
5. Display Entire Data
6. Exit
Enter your choice=1
Enter Database Name=school
Database created successfully
MENU
1. Create Database
2. Drop Database
3. Create Table
4. Insert Record
5. Display Entire Data
6. Exit
Enter your choice<1-6>=3
Table created successfully
MENU
1. Create Database
2. Drop Database
3. Create Table
4. Insert Record
5. Display Entire Data
6. Exit
Enter your choice<1-6>=4
Enter student rolino=11 Enter student name=Raj
Do you want to add more record=nProgram 14: Perform all the operations with reference to table ‘students’
through MySQL-Python connectivity.
copI
import mysql.connector as ms
db=ms.connect(
host="localhost”,
user="root",
password="root",
port = 3306,
)
#cn=db.cursor()
def insert_rec():
try:
while True:
nai
int(input("Enter roll number:"))
sname=input("Enter name:")
marks=float(input("Enter marks:"))
grzinput("Enter grade:"
cn.execute("insert into student
values({},'{},0,'{}')".format(rn,sname,marks,gr))
db.commit()
ch=input("Want more records? Press (N/n) to stop entry:")
if chin ‘Nn
print("Record inserted.
break
except Exception as e:
print("Error”, e)
def update_rec{):
try:rn=int(input(“Enter rollno to update:"))
marks=float(input("Enter new mart
))
er=input("Enter Grade:
cn.execute("update student set marks=(},gr="{}' where rn=()".format(marks,gr,rn))
db.commit()
print("Record Updated.
except Exception as e:
print("Error",e)
def delete_recl):
try
‘mzint(input("Enter rolino to delete:"))
cn.execute("delete from student where m=()" format(mn))
db.commit()
print("Record Deleted..
except Exception as e:
print("Error”,e)
def view_reci):
try
cn.execute("select * from student")
records = cn-fetchalll)
for record in records:
print(record)
fHdb.commit()
Hprint("Record...")
except Exception as e:
print("Error",e)
db = ms.connect(
host="localhost",
user="root",
password="root",
port=3306,database="daksh"
)
n= db.cursor()
while True:
print("MENU\n1. Insert Record\n2. Update Record \n3. Delete Record\n4. Display Record
\ns. Exit")
cheint(input("Enter your choice="))
3. Delete Record
4. Display Record
5. Exit
Enter your choice<1-4>=1
Enter roll number: 111
Enter name: Sagar
Enter marks:98Enter grade: Al
Want more records? Press (N/n) to stop entry: y
Enter roll number: 114
Enter name: Vipul
Enter marks:83
Enter grade: A2
Want more records? Press (N/n) to stop entry: n
MENU
1 Insert Record
2. Update Record
3, Delete Record
4. Display Record
5. Exit
Enter your choice=4
(1, ‘Amrita, Decimal('88,00'), 'A2')
(102, Jay, Decimal('98.00"), 'A1')
(211, ‘Sagar’, Decimal('98.00'), ‘A1")
(124, ‘Vipul’, Decimal(’83.00'), ‘A2')
MENU
1. Insert Record
2. Update Record
3, Delete Record
4. Display Record
5. Exit
Enter your choice<1-4>=2
Enter roll number to update:1
Enter new marks:98
Enter Grade: Al
MENU
1 Insert Record
2. Update Record3. Delete Record
4, Display Record
5. Exit
Enter your choice=4
(1, ‘Amrita, Decimal('98.00'), ‘A1')
(111, 'Sagar’, Decimal(’98.00'), ‘A1")
(114, Vipul’, Decimal(’83.00'),‘A2')
Enter your choice<1-4>=3
Enter roll number to delete:
MENU
1. Insert Record
2. Update Record
3, Delete Record
4, Display Record
5. Exit
Enter your choice=4
(102, Jay, Decimall'98.00"
1')
(111, ‘Sagar’, Decimal('98.00'), ‘A1')
(114, 'Vipul, Decimal('83.00', '2')
MENU
1 Insert Record
2. Update Record
3. Delete Record
4. Display Record
5. Exit
Enter your choicec1-4>=4
(202, Jay’, Decimal('98.00'), AL’)
(211, "Sagar’, Decimal('98.00’), ‘A1')
(124, Vipul’, Decimal(183.00'),‘A2')
MENU
1. Insert Record2. Update Record
3. Delete Record
4. Display Record
5. Exit
Enter your choice<1-4
5
THANKYOU