Aryan Cs Project
Aryan Cs Project
Aryan Cs Project
2023-24 Page1
TABLEOFCONTENTS:
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')
#ProgramThree:
def reverse(L):
print('originallist=',L)
print('reversedlist=',L[::-1])
reverse([1,2,3,4,5,6,7,8,9,10])
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
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()
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)
ETCount()
2023-24 Page13
13. WriteafunctionTRANSFER()inPython,whichshouldreadeachWordofatext file
#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()
#ProgramFifteen
2023-24 Page15
Info = []
defPush():
globalInfo
phn=int(input('PhoneNumber:'))
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
2023-24 Page19
insert()
20. Sartaj has created a table named Student in MYSQL database, SCHOOL:
QUESTIONNO.-1
TABLE:PRODUCT
2023-24 Page20
TABLE:CLIENT
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
TABLE:SALGRADE
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
Table:Client
C_ID ClientName City P_ID
01 CosmeticSoap Delhi FW05
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
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