0% found this document useful (0 votes)
22 views44 pages

CS Practical File 2023-24

Uploaded by

iram224669
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)
22 views44 pages

CS Practical File 2023-24

Uploaded by

iram224669
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/ 44

CENTRAL BOARD OF SECONDARY EDUCATION

Sacred Heart Convent Sr. Sec.


School Transport Nagar

A PRACTICAL RECORD FILE IS SUBMITTED TO DEPARTMENT OF COMPUTER


SCIENCE FOR THE PARTIAL FULLFILLMENT OF AISSCE EXAMINATION SESSION-
2023-24

SUBMITTED BY: FARDEEN KHAN


PGT CS :[MR. ATUL GANGWAR]
CLASS:[XII]
ROLLNO: [ ]

1
ACKNOWLEDGEMENT

I wish to express my deep sense of


gratitude and in debtedness to our learned
teacher MR.ATUL GANGWAR, PGT COMPUTER
SCIENCE,
[SACRED HEART CONVENT SR.SEC.SCHOOL]
for
His invaluable help, advice and guidance in
The preparation of this project.

I am also greatly indebted to our


principal [SR.CICILY LUKOSE] and school
authorities for providing me with the facilities
and requisite laboratory conditions for making
this practical file.

I also extend my thanks to a number of


teachers, my classmates and friends who helped
me to complete this practical file Successfully.

[FARDEEN KHAN]

2
3
CERTIFICATE

This is to certify that [FARDEEN KHAN]


, student of Class XII, [SACRED HEART
CONVENNT S
R.SEC.SCHOOL] has completed the TermII –
PRACTICAL FILE during the academic year [2023-
24] towards partial fulfillment of credit for
the Computer Science practical evaluation of
CBSE and submitted satisfactory report, as
compiled in the following pages, under my
supervision.

InternalExaminer ExternalExaminer
Signature Signature

Principal
Signature

4
No. Practical Date Signature
Program to enter two numbers and print
1
the arithmetic operations like +,-,*, /, //
and %.

Write a program to find whether an


2 inputted number is perfect or not.

Write a Program to check if the entered


3 number is Armstrong or not.

Write a Program to find factorial of the


4 entered number.

Write a Program to enter the number of


5
terms and to print the Fibonacci Series.

Write a Program to enter the string and to


6 check if it’s palindrome or not using loop.

Write a random number generator that


7 generates random numbers between 1
and 6 (simulatesa dice).

Read a text file line by line and display each


8 word separated by #.
Read a text file and display the number of
9 vowels/consonants/uppercase/lowercase
characters in the file.
Remove all the lines that contain the
10 character a’ in a file and write it to
another file.
Create a binary file with name and roll
11 number. Search for a given roll number
5
and display the name, if not found display
appropriate message.
12 Create a binary file with roll number,
name and marks. Input a roll number and
update the marks.
Create a CSV file by entering user-id and
13 password, read and search the password
for given user-id.
Write a python program to implement a
14 stack using a list data structure.
Write a menu-driven python program to
15 implement stackoperation.

16 Writeaprogram to implement astack for


theemployee details
(empno, name).
17 Write a python program to check whether
a string is a
palindromeor not using stack.
18 Queries Set 1 (Database Fetching records)
19 QueriesSet 2 (Based on Functions)
20 Queries Set 3 (DDL Commands)
21 Queries Set 4 (Group by , Order By)
22 Write a MySQL connectivity program in
Python to
Createadatabase school
Create a table students with the
specifications - ROLLNO integer,
STNAME character(10) in MySQL and
perform the following operations:
Insert two recordsin it
Displaythecontents of thetable
23 Perform all the operations with reference
to table ‘students’
through MySQL-Python connectivity.

6
7
1. Program to enter two numbers and print the arithmetic
operations like +,-,*, /, // and %.

OUTPUT-

2.Write a program to find whether an inputted number is


perfect or not.

OUTPUT-

8
3.Write a Program to check if the entered number is Armstrong
or not.

OUTPUT-

4. Write a Program to find factorial of the entered number.

OUTPUT-

5: Write a Program to enter the number of terms and to print


9
the Fibonacci Series.

OUTPUT-

6: Write a Program to enter the string and to check if it’s


palindrome or not using loop.

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.

10..Remove all the lines that contain the character a’ in a file


and write it to another file.
12
11.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.
13
output

12.Create a binary file with roll number, name and marks.


Input a roll number and update the marks.

14
OUTPUT-

15
13.Create a CSV file by entering user-id and password, read
and search the password for given user-id.

OUTPUT-

14.Write a python program to implement a stack using a list


data structure.

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

# Function that returns 1 if string is a


palindromedefisPalindrome(string):
globalstack
length=len(string)

#Allocatingthememoryforthestackstack=['0']*(l
ength+1)

# Finding the
midmid = length //
2i= 0
whilei<mid:

push(string[i]) i+= 1

# Checking if the length of the string is odd


thenneglectthemiddlecharacter

22
iflength%2!=0:
i+=1

# While not the end of the


stringwhilei<length:
ele=pop()

# If the characters differ then the given stringisnot


apalindrome
ifele !=
string[i]:returnFa
lse
i+=1
returnTrue
string=input("Enterstringtocheck:")

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;

c) select movieid, moviename, productioncost +


businesscost"totalearning"frommovie;

d) selectmovie_id,moviename,productioncostfrommoviewhe
reproducstis>150000and<1000000;

e) select moviename from movie where type ='action'


ortype='romance';

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.

MatchID MatchDate FirstTeamID SecondTeamID FirstTeamScore SecondTeamScore


M1 2021/12/20 1 2 107 93
M2 2021/12/21 3 4 156 158
M3 2021/12/22 1 3 86 81
M4 2021/12/23 2 4 65 67
M5 2021/12/24 1 4 52 88
M6 2021/12/25 2 3 97 68

Answers:

a) createdatabasesports;
30
b) Creatingtablewiththegivenspecification

create table team -> (teamidint(1), -


>teamnamevarchar(10),primarykey(teamid));

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;

b)select matchid, teamname, firstteamid,


secondteamid,matchdate from match_details, team
wherematch_details.firstteamid=team.teamid;

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:

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
S001 Sharpner 103 210 5 2018/06/11
S004 Compass 102 60 35 2018/05/10
S009 A4Papers 102 160 5 2018/07/17
a) Displayalltheitemsintheascendingorderofstockdate.
b) Displaymaximumpriceofitemsforeachdealerindividuallyasperdcodefromstock.
34
c) Displayalltheitemsindescendingordersofitemnames.
d) Displayaveragepriceofitemsforeachdealerindividuallyas perdocefromstockwhich
avergaepriceismorethan5.
e) Diisplaythesumofquantityforeachdcode.
Answers:
a) select*fromstockorderbystockdate;

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

You might also like