CS Practical File 2023-24
CS Practical File 2023-24
1
ACKNOWLEDGEMENT
[FARDEEN KHAN]
2
3
CERTIFICATE
InternalExaminer ExternalExaminer
Signature Signature
Principal
Signature
4
No. Practical Date Signature
Program to enter two numbers and print
1
the arithmetic operations like +,-,*, /, //
and %.
6
7
1. Program to enter two numbers and print the arithmetic
operations like +,-,*, /, // and %.
OUTPUT-
OUTPUT-
8
3.Write a Program to check if the entered number is Armstrong
or not.
OUTPUT-
OUTPUT-
OUTPUT-
OUTPUT-
10
7.Write a random number generator that generates
random numbers between 1 and 6 (simulatesa dice).
OUTPUT-
8.Read a text file line by line and display each word separated
by #.
OUTPUT-
11
9.Read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file.
14
OUTPUT-
15
13.Create a CSV file by entering user-id and password, read
and search the password for given user-id.
OUTPUT-
16
OUTPUT-
15. Writeamenu-drivenpythonprogramtoimplementstackoperation.Code:
defcheck_stack_isEmpty(stk):ifstk
==[]:
return
Trueelse:
returnFalse
# An empty list to store stack elements, initially emptys=[]
top=None#Thisistoppointerforpushandpop
defmain_menu():whi
leTrue:
print("Stack
Implementation")print("1- Push")
print("2-Pop")
print("3 -
Peek")print("4 -
Display")print("5-
Exit")
ch=int(input("Entertheyourchoice:"))ifch==1:
el=int(input("Enterthevaluetopushan
element:"))
push(s,el)
elifch==2:
e=pop_stack(s)
ife=="UnderFlow":
print("Stack is
underflow!")else:
print("Element
popped:",e)elifch==3:
e=pop_stack(s)
ife=="UnderFlow":
print("Stack is
underflow!")else:
print("The element on top
is:",e)elifch==4:
display(s)eli
17
fch==5:
break
else:
print("Sorry,Youhaveenteredinvalidoption")
def
push(stk,e):stk.ap
pend(e)top=len(stk
)-1
defdisplay(stk):
ifcheck_stack_isEmpty(stk):print
("StackisEmpty")
else:
top = len(stk)-
1print(stk[top],"-Top")
for i in range(top-1,-1,-
1):print(stk[i])
defpop_stack(stk):
ifcheck_stack_isEmpty(stk):retur
n"UnderFlow"
else:
e=stk.pop()iflen(
stk)==0:
top =
Noneelse:
top = len(stk)-
1returne
defpeek(stk):
ifcheck_stack_isEmpty(stk):retur
n"UnderFlow"
else:
top = len(stk)-
1returnstk[top]
Output:
18
16 Write a program to implement a stack for the employee details
(empno,name).Code:
stk=[]t
op=-1
def
line():print('~'*100
)
defisEmpty():glo
balstkifstk==[
]:
print("Stack is
empty!!!")else:
None
def
push():glob
al
stkglobalto
p
empno=int(input("Enter the employee number to
push:"))ename=input("Enter the employee name to
push:")stk.append([empno,ename])
19
top=len(stk)-1
def
display():glob
al
stkglobaltopif
top==-1:
isEmpty()e
lse:
top=len(stk)-
1print(stk[top],"<-top")
for i in range(top-1,-1,-
1):print(stk[i])
defpop_ele():glo
bal
stkglobaltopif
top==-1:
isEmpty()e
lse:
stk.pop()to
p=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:"))ifch==1:nm
push()
print("Element
Pushed")elifch==2:
pop_ele()e
lifch==3:dis
play()elifch
==4:
break
else:
print("InvalidChoice")
Output:
20
21
17- Writeapythonprogram tocheckwhetherastringisapalindromeornotusingstack.
Code:
stack =
[]top= -1
# push
functiondefpush(e
le):
global
toptop+=1
stack[top]=ele
# pop
functiondefpop()
:
globaltop
ele =
stack[top]top-= 1
returnele
#Allocatingthememoryforthestackstack=['0']*(l
ength+1)
# Finding the
midmid = length //
2i= 0
whilei<mid:
push(string[i]) i+= 1
22
iflength%2!=0:
i+=1
ifisPalindrome(string):
print("Yes,thestringisapalindrome")
else:
print("No,thestringisnotapalindrome")
Output:
23
PARTBSQLQUERIES
1. ConsiderthefollowingMOVIEtableandwritetheSQLqueriesbasedonit.
Movie_ID MovieName Type ReleaseDate ProductionCost BusinessCost
M001 TheKashmir Files Action 2022/01/26 1245000 1300000
M002 Attack Action 2022/01/28 1120000 1250000
M003 LooopLapeta Thriller 2022/02/01 250000 300000
M004 Badhai Do Drama 2022/02/04 720000 68000
M005 ShabaashMithu Biography 2022/02/04 1000000 800000
M006 Gehraiyaan Romance 2022/02/11 150000 120000
a) Displayallinformationfrommovie.
b) Displaythetypeofmovies.
c) Display movieid, moviename, total_eraning by showing the business done by
themovies.Claculatethebusinessdonebymovieusingthesumofproductioncostandbusi
nesscost.
d) Displaymovieid,movienameandproductioncostforallmovieswithprod
uctioncostgreater thatn 150000 andlessthan1000000.
e) Displaythemovieoftypeactionandromance.
f) DisplaythelistofmovieswhicharegoingtoreleaseinFebruary,2022.Answe
rs:
a)select*frommovie;
24
b) selectdistinctfromamovie;
d) selectmovie_id,moviename,productioncostfrommoviewhe
reproducstis>150000and<1000000;
25
f) selectmovienamefrommoviewwheremonth(releasedate)=2;
2. Writefollowingqueries:
a) Writeaquerytodisplaycubeof5.
b) Writeaquerytodisplaythenumber563.854741roundingofftothenexthnudred.
c) Writeaquerytodisplay"put"fromtheword"Computer".
d) Writeaquerytodisplaytoday'sdateintoDD.MM.YYYYformat.
e) Writea querytodisplay'DIA'fromtheword"MEDIA".
f) Writeaquerytodisplaymoviename-typefromthetablemovie.
g) Writeaquerytodisplayfirstfourdigitsofproductioncost.
h) Writea querytodisplaylastfourdigitsofbusinesscost.
i) Writeaquerytodisplayweekdayofreleasedates.
j) Writeaquerytodisplaydaynameonwhichmoviesaregoingtobereleased.
Answers:
a)selectpow(5,3);
b)selectround(563.854741,-2);
26
c)selectmid("Computer",4,3);
d)select concat(day(now()),
concat('.',month(now()),concat('.',year(now()))))"
Date";
e)selectright("Media",3);
f)selectconcat(moviename,concat('-',type))frommovie;
g)selectleft(productioncost,4)frommovie;
27
28
h)selectright(businesscost,4)frommovie;
i)selectweekday(releasedate)frommovie;
j)selectdayname(releasedate)frommovie;
29
3. Suppose your school management has decided to conduct cricket matches
betweenstudents of Class XI and Class XII. Students of each class are asked to join
any oneofthe four teams–
TeamTitan,TeamRockers,TeamMagnetandTeamHurricane. During summer
vacations, various matches will be conducted betweentheseteams.Help
yoursportsteacherto do thefollowing:
a) Createadatabase“Sports”.
b) Createatable“TEAM”withfollowingconsiderations:
a. ItshouldhaveacolumnTeamIDforstoringanintegervaluebetween1to9,which
referstouniqueidentificationofateam.
b. Each TeamID should have its associated name (TeamName), which should be
astring of length notlessthan10characters.
c. Usingtablelevelconstraint, makeTeamIDastheprimarykey.
c) ShowthestructureofthetableTEAM usingaSQLstatement.
d) As per the preferences of the students four teams were formed as given below.
Insertthesefour rowsinTEAMtable:
a. Row1:(1, Tehlka)
b. Row2:(2, Toofan)
c. Row3:(3, Aandhi)
d. Row3:(4,Shailab)
e) Showthecontents ofthetableTEAM usingaDMLstatement.
f) Now create another table MATCH_DETAILS and insert data as shown below.
Chooseappropriatedatatypesand constraintsforeach attribute.
Answers:
a) createdatabasesports;
30
b) Creatingtablewiththegivenspecification
c) descteam;
Insertingdata:
mqsql>insertintoteam->values(1,'Tehlka');
Showthecontentoftable-team:
select*fromteam;
31
Creatinganothertable:
createtablematch_details
->(matchidvarchar(2)primarykey,
->matchdatedate,
->firstteamidint(1)referencesteam(teamid),
->secondteamidint(1)referencesteam(teamid),
->firstteamscoreint(3),
->secondteamscoreint(3));
4. Writefollowingqueries:
a) Displaythematchid,teamid,teamscorewhoscoredmorethan70infirstiningalong
32
withteamname.
b) Displaymat
c) chid,teamnameandsecondteamscorebetween100to160.
d) Displaymatchid,teamnamesalongwithmatchdates.
e) Displayuniqueteamnames
f) DisplaymatchidandmatchdateplayedbyAnadhiandShailab.
Answers:
a)selectmatch_details.matchid,match_details.firstteamid,t
eam.teamname,match_details.firstteamscore
frommatch_details, team where match_details.firstteamid
=team.teamidandmatch_details.first
selectmatch_details.matchid,match_details.firstteamid,team.te
amname,match_details.firstteamscore frommatch_details, team
where match_details.firstteamid
=team.teamidandmatch_details.firstteamscore>70;
33
c)selectdistinct(teamname)frommatch_details,teamwherematc
h_details.firstteamid =team.teamid;
d)selectmatchid,matchdatefrommatch_details,teamwherematc
h_details.firstteamid = team.teamid
andteam.teamnamein('Aandhi','Shailab');
5. Considerthefollowingtableandwritethequeries:
35
b) selectdcode,max(unitprice)fromstockgroupbycode;
c) select*fromstockorderbyitemdesc;
d)selectdcode,avg(unitprice)fromstockgroupbydcodehavin
gavg(unitprice)>5;
e) selectdcode,sum(qty)fromstockgroupbydcode;
36
PYTHONDATABASECONNECTIVITY
1. WriteaMySQLconnectivityprograminPythonto
Createadatabaseschool
Createatablestudentswiththespecifications-
ROLLNOinteger,STNAMEcharacter(10)in MySQLand perform
thefollowing operations:
o Inserttworecordsinit
o Displaythecontents ofthetable
2. Performalltheoperationswithreferenceto table‘students’throughMySQL-
Pythonconnectivity.
Answers:
1.Usingpymysql-Code:
importpymysqlasms
#FunctiontocreateDatabaseasperuserschoicedefc_data
base():
try:
dn=input("Enter Database
Name=")c.execute("create database
{}".format(dn))c.execute("use
{}".format(dn))print("Databasecreatedsucce
ssfully")
except Exception as
a:print("DatabaseError",a)
#FunctiontoDropDatabaseasperuserschoicedefd_da
tabase():
try:
dn=input("Enter Database Name to be
dropped=")c.execute("drop database
{}".format(dn))print("Databasedeletedsucessful
ly")
except Exception as
a:print("DatabaseDropError",a)
#Function to create
Tabledefc_table():
try:
c.execute('''create table
students(
rollnoint(3),stnam
evarchar(20)
);''
')
print("Table created
successfully")exceptExceptionasa:
37
print("CreateTableError",a)
#FunctiontoInsertData
defe_data():try:
whileTrue:
rno=int(input("Enterstudentrollno="))name=in
put("Enter student name=")
c.execute("use
{}".format('school'))c.execute("insertintost
udents
values({},'{}');".format(rno,name))db.c
ommit()
choice=input("Do you want to add more
record<y/n>=")ifchoice in"Nn":
break
except Exception as
a:print("InsertRecordError",a)
#Function to Display
Datadefd_data():
try:
c.execute("select * from
students")data=c.fetchall()
for i in
data:print(i
)
except Exception as
a:print("DisplayRecordError",a)
db=ms.connect(host="localhost",user="root",password="root")c=db.c
ursor()
whileTrue:
print("MENU\n1.CreateDatabase\n2.DropDatabase\n3.
Create Table\n4. Insert Record \n5. Display Entire Data\
n6.Exit")
choice=int(input("Enter your choice<1-
6>="))ifchoice==1:
c_database()e
lifchoice==2:
d_database()e
lifchoice==3:
c_table()elif
choice==4:
38
e_data()elifc
hoice==5:
d_data()elifc
hoice==6:
break
else:
print("Wrongoptionselected")
Output:
39
usingmysqlconnector
importmysql.connector as
msdb=ms.connect(host="localhost",user="root",passwd="root",database
='school')
cn=db.cursor()def
insert_rec():
try:
whileTrue:
rn=int(input("Enter roll
number:"))sname=input("Enter
name:")marks=float(input("Enter
marks:"))gr=input("Enter
grade:")cn.execute("insertintostude
nts
values({},'{}',
{},'{}')".format(rn,sname,marks,gr))db.commit()
ch=input("Wantmorerecords?Press(N/n)tostopentry:")
ifch in
'Nn':break
except Exception as
e:print("Error",e)
defupdate_rec():t
ry:
rn=int(input("Enterrollnotoupdate:"))marks=float(in
put("Enter new marks:"))gr=input("EnterGrade:")
cn.execute("updatestudentssetmarks={},grade='{}'whe
rerno={}".format(marks,gr,rn))
db.commit()exceptE
xceptionase:
print("Error",e)
defdelete_rec():t
ry:
rn=int(input("Enterrollnotodelete:"))cn.execute("de
letefromstudentswhere
rno={}".format(rn))
db.commit()exceptE
xceptionase:
print("Error",e)
40
defview_rec():t
ry:
cn.execute("select*fromstudents")
41
except Exception as
e:print("Error",e)
whileTrue:
print("MENU\n1. Insert Record\n2. Update Record \n3.
DeleteRecord\n4.DisplayRecord\n5.Exit")
ch=int(input("Enter your choice<1-
4>="))ifch==1:
insert_rec()
elifch==2:
update_rec()
elifch==3:
delete_rec()
elifch==4:
view_rec()
elifch==5:
break
else:
print("Wrongoptionselected")
Output:
42
43
44