ARYAN GAUTAM
2023-24 Page1
TABLEOFCONTENTS:
S.NO PROGRAM TEACHERSIGN
1 FUNCTIONS
2 TEXTFILES
3 BINARYFILES
4 CSVFILES
5 STACK
6 PYTHON–MYSQLDATABASECONNECTIVITY
7 SQLQUERIES
2023-24 Page2
1. Write a function countNow(PLACES) in Python, that takes the
dictionaryPLACES as an argument and displays the names (in uppercase)of
the placeswhose names are longer than 5 characters. For example, Consider
the following dictionary PLACES={1:"Delhi",2:"London",3:"Paris",4:"New
York",5:"Doha"}
Theoutputshouldbe:LONDONNEWYORK#Pr
ogram One:
def countNow(PLACES):for
k,vin PLACES.items():
if len(v)>5:
print(v.upper())
places={1:'Delhi',2:'London',3:'NewYork',5:'Doha'}
countNow(places)
2. Write a function, lenWords(STRING), that takes a string as an argument
andreturns a tuple containing length of each word of a string. For example, if
thestring is "Come let us have some fun", the tuple will have (4, 3, 2, 4, 4, 3)
#ProgramTwo:
deflenWords(string):
s=string.split()
t=()
for k in s:
t+=(len(k),)
print(t)
2023-24 Page3
lenWords('projectshouldbesubmittedbyeveryone')
3. Define afunction to acceptalist of 10numbers andreturna list
containingreverse of the list.
#ProgramThree:
def reverse(L):
print('originallist=',L)
print('reversedlist=',L[::-1])
reverse([1,2,3,4,5,6,7,8,9,10])
4. Defineafunctiontoacceptalistof10numbersandexchangethefirsthalf elements with
second half.
#ProgramFour:
def exchange(l):
print('originallist=',l)
L=l[5:] + l[:5]
print('modified list=',L)
exchange([1,2,3,4,5,6,7,8,9,10])
5. Considerafile,SPORT.DAT,containingrecordsofthefollowingstructure:[SportNa
me, TeamName, No_Players]
Writeafunction,copyData(),thatreadscontentsfromthefileSPORT.DATandcopi
estherecordswithSportnameas“BasketBall”tothefilenamed
2023-24 Page4
BASKET.DAT. The function should return the total number of records
copiedto the file BASKET.DAT.
#ProgramFive
def copyData():
a=open('sport.dat','rb')
b=open('basket.dat','wb')
try:
c=0
while True:
l=p.load(a)
ifl[0]=='basketball':
p.dump(l,b);c+=1
except EOFError:
a.close();b.close()
print(c)
copyData()
6. A Binary file, CINEMA.DAT has the following structure:
{MNO:[MNAME,MTYPE]} Where MNO – Movie Number MNAME – Movie Name
MTYPE isMovie Type Write a user defined function, findType(mtype), that
acceptsmtype as parameter and displays all the records from the binary
fileCINEMA.DAT, that have the value of Movie Type as mtype.
#ProgramSix:
import pickle as
pdeffindType(mtyp):
2023-24 Page5
a=open('cinema.dat','rb')
try:
while True:
d=p.load(a)
l=d[mno]
ifl[1]==mtype:
print(d)
exceptEOFError:
a.close()
findType('comedy')
7. Write a Program in Python that defines and calls the following user
definedfunctions: (i) ADD() – To accept and add data of an employee to a CSV
file‘record.csv’. Each record consists of a list with field elements as empid,
nameand mobile to store employee id, employee name and employee
salaryrespectively. (ii) COUNTR() – To count the number of records present
in theCSV file named ‘record.csv’.
importcsv
def add():
a=open('record.csv','w',newline='\r\n')
w=csv.writer(a,delimiter=',')
2023-24 Page6
for k in range(2):
eid=input('employee id=')
ename=input('employeename=')
salary=int(input('salary='))
w.writerow([eid,ename,salary])
a.close()
defcountr():
a=open('record.csv','r',newline='\r\n')
r=csv.reader(a,delimiter=',')
c=0
forkinr:
ifk!=False:
c+=1
print(c)
a.close()
add()
countr()
8. Write a Program in Python that defines and calls the following user
definedfunctions:(i)add()–ToacceptandadddataofanemployeetoaCSVfile
2023-24 Page7
‘furdata.csv’. Each record consists of a list with field elements as fid,
fnameand fprice to store furniture id, furniture name and furniture
pricerespectively. (ii) search()- To display the records of the furniture
whoseprice is more than 10000.
#ProgramEight:
importcsv
def add():
a=open('furdata.csv','w',newline='\r\n')
w=csv.writer(a,delimiter=',')
for k in range(2):
fid=input('furniture id=')
fname=input('furniturename=')
fprice=int(input('furnitureprice='))
w.writerow([fid,fname,fprice])
a.close()
defsearch():
a=open('furdata.csv','r',newline='\r\n')
r=csv.reader(a,delimiter=',')
forkinr:
ifk[-1]>10000:
2023-24 Page8
print(k)
a.close()
add()
search()
9. Write a Program in Python that defines and calls the following user
definedfunctions:
(i) add() – To accept and add data of 10 employee to a binary
file‘furdata.dat’. Each record consists of a list store furniture id,
furniturename and furniture price respectively.
(ii) search()- To return number ofthe records of the furniture whoseprice
is more than 10000.
(iii) Modify():toincreasepriceby20%wherefurnitureis‘chair’or‘table’
#ProgramNine:
importpickleasp def
add():
a=open('furdata.dat','wb')
for k in range(10):
fd=input('furniture id=')
fn=input('furniture name=')
fp=int(input('furnitureprice='))
p.dump([fd,fn,fp],a)
2023-24 Page9
a.close()
add()
def search():
a=open('furdata.dat','rb')
try:
c=0
while True:
l=p.load(a)
ifl[-1]>10000:
c+=1
except EOFError:
a.close();print(c)
search()
def modify():
a=open('furdata.dat','rb+')
try:
while True:
pos=a.tell()
d=p.load(a)
2023-24 Page10
ifd[1]in['table','chair']:
d[-1]+=d[-1]*0.20
a.seek(pos,0)
p.dump(d,b)
except EOFError:
a.close
modify()
10. Vedansh is a Python programmer working in a school. For the Annual
SportsEvent, he has created a csv file named Result.csv, to store the results
ofstudents in different sports events.
The structure of Result.csv is : [St_Id, St_Name, Game_Name, Result]
WhereSt_Id is Student ID (integer) ST_name is Student Name (string)
Game_Name isname of game in which student is participating(string) Result
is result of thegame whose value can be either 'Won', 'Lost' or 'Tie' For
efficientlymaintaining data of the event, Vedansh wants to write the
following userdefined functions:
Accept() – to accept a record from the user and add it to the file
Result.csv.The column headings should also be added on top of the csv file.
wonCount() – to count the number of students who have won any event. As
aPython expert, help him complete the task
#ProgramTen:
import csv
2023-24 Page11
def Accept():
a=open('Result.csv','a',newline='\r\n')
w=csv.writer(a, delimiter=',')
i=int(input('student id='))
n=input('student name=')
g=nput('gamename=')
r=input('result= =')
wr.writerow([i,n,g,r])
def wonCount():
a=open('Result.csv','r',newline='\r\n')
r = csv.reader(a, delimiter=',')
c=0
for k in r:
print(k)
ifk[-1]=='won':
c+=1
print(c)
Accept()
wonCount()
11. WriteamethodCOUNTLINES()inPythontoreadlinesfromtextfile‘TESTFILE.TXT’
and display the lines which are not starting with any vowel.
#ProgramEleven
defCOUNTLINES():
a=open('TESTFILE.txt','r')
for k in a.readlines():
2023-24 Page12
r=k.strip()
ifr[0]notin'aeiouAEIOU'): print(k)
COUNTLINES()
12. Write a function ETCount() in Python, which should read each character of
atext file “TESTFILE.TXT” and then count and display the count of
occurrenceof alphabets E and T individually (including small cases e and t
too).
#ProgramTwelve
def ETCount():
a=open('TESTFILE.txt','r')
e=0;t=0
forkina.read(): if
k in ['e','E']:
e+=1
ifkin['t','T']:
t+=1
print('countofoccurenceofe=',e)
print('count of occurence of t=',t)
ETCount()
2023-24 Page13
13. WriteafunctionTRANSFER()inPython,whichshouldreadeachWordofatext file
“TESTFILE.TXT” and then copy the words containing vowels to r.txt.
#ProgramThriteen
defTRANSFER():
a=open('TESTFILE.txt','r'):
b=open('r.txt','w')
forkina.read().split():
for i in k:
ifiin'aeiouAEIOU':
b.write(k+'\n')
TRANSFER()
14. A list, NList contains following record as list elements: [City, Country,distance
from Delhi] Each of these records are nested together to form anested list.
Write the following user defined functions in Python to performthe specified
operations on the stack named travel.
(i) Push_element(NList): It takes the nested list as an argument andpushes
a list object containing name of the city and country, which arenot in
India and distance is less than 3500 km from Delhi.
(ii) Pop_element(): It pops the objects from the stack and displays
them.Also, the function should display “Stack Empty” when there are
noelements in the stack.
#ProgramFourteen
2023-24 Page14
travel=[]
defPush_element(NList):
for k in NList:
ifk[1]!='India'andk[-1]<3500:
travel.append(k)
defPop_element():
if travel:
p=travel.pop()
print(p)
else:
print('Stackisempty')
Push_element(NList)
Pop_element()
15. A list contains following record of a customer:
[Customer_name,Phone_number, City] Write the following user defined
functions to performgivenoperations onthe stack named
‘status’:(i)Push_element() - ToPush anobject containing name and Phone
number of customers who live in Goa tothe stack (ii) Pop_element() - To Pop
the objects from the stack and displaythem. Also, display “Stack Empty”
when there are no elements in the stack.
#ProgramFifteen
2023-24 Page15
Info = []
defPush():
globalInfo
name = input('Customer Name: ')
phn=int(input('PhoneNumber:'))
city = input('City: ')
if city == 'Goa':
Info.append([name,phn,city])
defPop_element():
global nlist
if nlist:
item=nlist.pop()
print(item)
else:
print('StackEmpty')
Push()
Pop_element()
16. WriteafunctioninPython,Push(SItem)where,SItemisadictionarycontainingthe
detailsofstationaryitems–{Sname:price}.Thefunction
2023-24 Page16
shouldpushthenamesofthoseitemsinthestackwhohavepricegreaterthan75.Alsodi
splaythecountofelementspushedintothestack.Forexample: If the dictionary
contains the following
data:Ditem={"Pen":106,"Pencil":59,"Notebook":80,"Eraser":25}Thestackshouldc
ontain Notebook Pen.
Theoutputshouldbe:Thecountofelementsinthestackis2#Prog
ram Sixteen
stack=[]
defPush(SItem):
c=0
forkinSItem:
if SItem[k] > 75:
stack.append(k)
c+=1
print('Thecountofelementsinthestackis:',c) Push(SItem)
17. Definea function to makea connection witha database hospital
andreadtherecords from doctor table where doctor have degree in ‘ortho’
and salarymore than 20000.
Tableschemais:Doctor(#code,dname,degree,sal,dob)#
Program Seventeen
defconection():
importmysql.connectorasm
cn = m.connect(host='localhost', user='root', passwd='lps123',
database='hostpital')
cr= cn.cursor()
2023-24 Page17
d=input('degree=')
s=int(input('salary='))
q="select*fromdoctorwheredegree='{}'andsalary>{};".format(d,s) cr.execute(q)
d=cr.fetchall()
for k in d:
print(k)
cn.close()
connection()
18. Defineafunctiontomakeaconnectionwithadatabasehospital andincreasethe
salary by 40% where doctor salary is between A and B.[user will pass Aand B
to function)
Tableschemais:Doctor(#code,dname,degree,sal,dob)#
Program Eighteen
defmodify():
importmysql.connectorasm
cn=m.connect(host='localhost', user='root', passwd='lps123',
database='hostpital')
crcn.cursor()
A=int(input('Lower salary limit='))
B=int(input('Highersalarylimit='))
q="updatedoctorsetsalary=salary+salary*0.40wheresalarybetween{}and
{};".format(A,B)
cr.execute(q)
cn.commit()
cn.close()
2023-24 Page18
modify()
19. KabirwantstowriteaprograminPythontoinsertthefollowingrecordinthe table
named Student in MYSQL database, SCHOOL:
rno(Rollnumber)-integer
name(Name)-string
DOB(Dateofbirth)– Date
Fee – float Note the following to establish connectivity between Python
andMySQL:
Username-rootPassword-tiger
Host-localhostThevaluesoffieldsrno,name,DOBandfeehastobeaccepted from
the user.
HelpKabirtowritetheprograminPython.#Pr
ogram Nineteen
defadd():
importmysql.connectorasm
cn=m.connect(host='localhost',user='root',passwd='tiger',database='SCHOOL')
cr=cn.cursor()
r=int(input('roll no.='))
n=input('name=')
dob=input('dateofbirth=')
f=float(input('fee='))
q="insertintoStudentvalues({},'{}','{}',{});"
q=q.format(r, n,dob,f)
cr.execute(q)
cn.commit()
cn.close()
2023-24 Page19
insert()
20. Sartaj has created a table named Student in MYSQL database, SCHOOL:
rno(Roll number )- integer name(Name) - string DOB (Date of birth) –
Date Fee – float Note the following to establish connectivity betweenPython
and MySQL: Username - root Password - tiger Host – localhostSartaj, now
wants to display the records of students whose fee is more than5000. Help
Sartaj to write the program in Python.
#ProgramTwenty
defdisplay():
importmysql.connectorasm
cnm.connect(host='localhost',user='root',passwd='tiger',database='SCHOOL')
cr=cn.cursor()
cr.execute("select*fromStudentwherefee>5000;") d=cr.fetchall()
for k in d:
print(k)
display()
QUESTIONNO.-1
TABLE:PRODUCT
P_ID PRODUCTNAME MANUFACTURE PRICE
101 Talcompowder LAK 40
102 Face wash ABC 45
103 Bath soap ABC 55
104 Shampoo XYZ 120
105 Face wash XYZ 95
2023-24 Page20
TABLE:CLIENT
C_ID CLIENTNAME CITY P_ID
1 Cosmeticshop Delhi 102
2 Totalhealth Mumbai 103
3 Livelife Delhi 104
4 Prettywoman Delhi 105
5 Dreams Lucknow 101
GIVESUITABLESQLCOMMANDFORDOINGGIVENACTIONS-
1. TodisplaythedetailsofthoseclientswhosecityisDelhi.
> SELECT*FROMCLIENTWHERECITY='Delhi';
2. Todisplaythedetailsofproductswhosepriceisintherangeof50to100.
>SELECT*FROMPRODUCTWHEREPRICEBETWEEN50AND100;
3. Todisplaytheclientname,cityfromtableclient,andProductnameandPricefromtableproduct.
4. >SELECTCLIENTNAME,CITY,PRODUCTNAME,PRICEFROMPRODUCTA,CLIENTBWHERE
A.P_ID=B.P_ID;
5. Toincreasethepriceofallproductsby10.
> UPDATEPRODUCTSETPRICE=PRICE+10;
GIVEOUTPUTOFGIVENQUERY-
6. SELECTDISTINCTcityFROMclient;
7. SELECTManufacture,MAX(price),MIN(price),Count(*)FROMProductGROUPBYmanufacture;
2023-24 Page21
8. SELECTclientname,manufactureFROMProductA,ClientBWHEREA.P_ID=B.P_ID;
9. SELECTproductname,price*4FROMProduct;
QUESTIONNO.-2
TABLE:EMPLOYEE
ECODE NAME DESIG SGRADE DOJ DOB
101 Abdul Ahmad EXECUTIVE S03 2003-03-23 1980-01-13
102 RaviChander HEAD-IT S02 2010-02-12 1987-07-22
103 JohnKen RECEPTIONIST S03 2009-06-24 1983-02-24
104 NazarAmeen GM S02 2006-08-11 1984-03-03
105 PriyamSen CEO S01 2004-12-29 1982-01-19
TABLE:SALGRADE
SGRADE SALARY HRA
S01 56000 18000
S02 32000 12000
S03 24000 8000
2023-24 Page22
GIVESUITABLESQLCOMMANDFORDOINGGIVENACTIONS-
1. TodisplaythedetailsofallemployeesindescendingorderofDOJ.
>SELECT*FROMEMPLOYEENATURALJOINSALGRADEORDERBYDOJASC:
2. TodisplayNAMEandDESIGofthoseemployeeswhosesalgradeiseitherS02orS03
>SELECTNAME,DESIGFROMEMPLOYEEWHERESGRADE='S02'ORSGRADE='S02';.
3. TodisplaythecontentofalltheemployeestablewhoseDOJisinbetween‘2006-02-09’and ‘2009-
08-08’.
>SELECT*FROMEMPLOYEENATURALJOINSALGRADEWHEREDOJ⏴'2006-02-09'AND
DOJ>'2009-08-08';
GIVEOUTPUTOFGIVENQUERY-
4. SELECTCOUNT(SGRADE),SGRADEFROMEMPLOYEEGROUPBYSGRADE;
5. SELECTMIN(dob),MAX(doj)FROMEmployee;
6. SELECTname,salaryFROMEmployeeE,SalgradeSWHEREE.sgrade=S.sgradeANDE.ecode<103;
7. SELECTsgrade,salary+hraAS“income”FROMSalgradeWHEREsgrade=’S02’;
8. CREATEVIEWEmpASSELECT*FROMEmployee;
ConsiderthefollowingtableProductandClient.WritetheSQLcommandsfrothe
statement (I) to (IV) and give output for SQL quires (V) to (VIII) .
QUESTIONNO.-3
Table:Product
2023-24 Page23
P_ID ProductName Manufacture Price
TP01 TalcomPowder LAK 40
FW05 FaceWash ABC 45
BS01 BathSoap ABC 55
SH06 Shampoo XYZ 120
FW12 Fash Wash XYZ 95
Table:Client
C_ID ClientName City P_ID
01 CosmeticSoap Delhi FW05
06 TotalHealth Mumbai BS01
12 LiveLife Delhi SH06
15 PrettyWomen Delhi FW12
16 Dreams Bangalore TP01
WRITESQLQUERIES:
(i) TodisplaythedetailsofthoseclientswhosecityisDelhi.
> SELECT*FROMCLIENTWHERECITY='Delhi';
(ii) Todisplaythedetailofproductwhosepriceisintherangeof50to
hundred (both values included ) .
> SELECT*FROMPRODUCTWHEREPRICEBETWEEN50AND100
(iii) To display the Client Name, City from table client ,and product name
andpricefromtableproduct,withtherecorrespondingmatchingP_ID.
> SELECTCLIENTNAME,CITY,PRODUCTNAME,PRICEFROMCLIENTB,PRODUCTA
(iv) Toincreasethepriceofallproductsby10.
> UpdateProductsetprice=price+10;
GIVEOUTPUTS:
2023-24 Page24
(v) SELECTDISTINCTCityFROMClient;
a.
(vi) SELECTManufacture,MAX(Price),MIN(Price),Count(*)FROMProduct
GROUP BY Manufacture;
(vii)
(viii) SELECTClientName,ManufactureNameFromProduct,ClientWHERE
Client.C_ID = Product.P_ID;
(ix) SELECTProductName,Price*4FROMProduct;
1.
2023-24 Page25
CosiderthefollowingtableStockandDelearsandanswer(a1)and(a2)paorofthis
question:
QUESTIONNO.-4
Table:Stock
ItemNo Item Dcode Qty UnitPrice StockDate
5005 BallPen0.5 102 100 16 31-Mar-10
5003 BallPen0.25 102 150 20 01-jan-10
5002 GelPen Premiun 101 125 14 14-feb-10
5006 GelPen Classic 01 200 22 01-Jan-09
5001 EraserSmall 102 210 5 19-Mar-09
5004 Eraser Big 102 60 10 12-Dec-09
5009 SharpnerClassic 103 160 8 23-Jan-09
Table:Dealers
Dcode Dname
101 ReliableStationaries
103 ClassicPlastics
102 ClearDeals
(a1)WriteSQLcommandsforthefollowing statements:
(i) Todisplaydetailsofallitemsinthestocktableinascendingorder of
stockDate.
>SELECT*FROMSTOCKORDERBYSTOCKDATE;
(ii) TodisplayItemNoandItemNameofthoseitemsfromstocktable
whose unite price is more then Rs 10.
2023-24 Page26
> SELECTITEM,ITEMNOFROMSTOCKWHEREUNITPRICE>10;
(iii) Todisplaythedetailsofthoseitemswhosedealerscode(Dcode)is 102
or Qty in Stock is more than 100 from the table Stock.
> SELECT*FROMSTOCKWHEREDCODE=102ORQTY>100;
(iv) Todisplaymaximumunitpriceofitemsforeachdealers
individually as per Dcode from the table Stock.
> SELECTDNAME,MAX(UNITPRICE)FROMSTOCKA,DEALERSBWHERE
A.DCODE=B.DCODEGROUPBYDNAME;
(a2)GivetheoutputofthefollowingSQL queries:
(v) SELECTCOUNT(DISTINCTDcode)FROMStock;
(vi) SELECTQty*UnitPriceFROMStockWHEREItemNo=5006;
(vii) SELECTItem,DnameFROMStockS,DelearsDWHERE
S.Dcode=D.Dcode AND ItemNo=5004;
(viii) SELECTMIN(StockDate)FROMStock;
2023-24 Page27
2023-24 Page28