SlideShare a Scribd company logo
COMPUTER SCIENCE WITH PYTHON
PROGRAM FILE
NAME:
CLASS:
SECTION:
INDEX
S.NO TOPIC T.SIGN
1 Write the definition of a function Alter(A, N) in python, which should
change all the multiples of 5 in the list to 5 and rest of the elements as 0.
2 Write a code in python for a function void Convert ( T, N) , which
repositions all the elements of array by shifting each of them to next
position and shifting last element to first position.
3 Create a function showEmployee() in such a way that it should accept
employee name, and it’s salary and display both, and if the salary is
missing in function call it should show it as 9000
4 Write a program using function which accept two integers as an
argument and return its sum. Call this function and print the results in
main( )
5 Write a definition for function Itemadd () to insert record into the binary
file ITEMS.DAT,
(items.dat- id,gift,cost). info should stored in the form of list.
6 Write a definition for function SHOWINFO() to read each record of a
binary file ITEMS.DAT,
(items.dat- id,gift,cost).Assume that info is stored in the form of list
7 Write a definition for function COSTLY() to read each record of a binary
file ITEMS.DAT, find and display those items, which are priced less than
50. (items.dat- id,gift,cost).Assume that info is stored in the form of list
8 A csv file counties.csv contains data in the following order:
country,capital,code
sample of counties.csv is given below:
india,newdelhi,ii
us,washington,uu
malaysia,ualaumpur,mm
france,paris,ff
write a python function to read the file counties.csv and display the
names of all those
countries whose no of characters in the capital are more than 6.
9 write a python function to search and display the record of that product
from the file PRODUCT.CSV which has maximum cost.
sample of product.csv is given below:
pid,pname,cost,quantity
p1,brush,50,200
p2,toothbrush,120,150
p3,comb,40,300
p4,sheets,100,500
p5,pen,10,250
10 write a python function to find transfer only those records from the file
product.csv to another file "pro1.csv"whose quantity is more than 150.
also include the first row with headings
sample of product.csv is given below:
pid,pname,cost,quantity
p1,brush,50,200
p2,toothbrush,120,150
p3,comb,40,300
p4,sheets,100,500
p5,pen,10,250
11 WAP to find no of lines starting with F in firewall.txt
12 WAP to find how many 'f' and 's' present in a text file
13 Write a program that reads character from the keyboard one by one. All
lower case characters get store inside the file LOWER, all upper case
characters get stored inside the file UPPER and all other characters get
stored inside OTHERS.
14 WAP to find how many 'firewall' or 'to' present in a file firewall.txt
15 A linear stack called "List" contain the following information:
a. Roll Number of student
b. Name of student
Write add(List) and pop(List) methods in python to add and remove
from the stack.
16 Consider the tables GARMENT and FABRIC, Write SQL commands for the
statements (i) to (iv)
17 Write SQL commands for (a) to (f) on the basis of Teacher relation
18 Write a MySQL-Python connectivity code display ename,
empno,designation, sal of those employees whose salary is more than
3000 from the table emp . Name of the database is “Emgt”
19 Write a MySQL-Python connectivity code increase the salary(sal) by 300
of those employees whose designation(job) is clerk from the table emp.
Name of the database is “Emgt”
Q1
Write the definition of a function Alter(A, N) in python, which should change all the multiples
of 5 in the list to 5 and rest of the elements as 0.
#sol
def Alter ( A, N):
for i in range(N):
if(A[i]%5==0):
A[i]=5
else:
A[i]=0
print("LIst after Alteration", A)
d=[10,14,15,21]
print("Original list",d)
r=len(d)
Alter(d,r)
'''
OUTPUT
Original list [10, 14, 15, 21]
LIst after Alteration [5, 0, 5, 0]
'''
Q2
Write a code in python for a function void Convert ( T, N) , which repositions all the elements
of array by shifting each of them to next position and shifting last element to first position.
e.g. if the content of array is
0 1 2 3
10 14 11 21
The changed array content will be:
0 1 2 3
21 10 14 11
sol:
def Convert ( T, N):
for i in range(N):
t=T[N-1]
T[N-1]=T[i]
T[i]=t
print("LIst after conversion", T)
d=[10,14,11,21]
print("original list",d)
r=len(d)
Convert(d,r)
OUTPUT:
original list [10, 14, 11, 21]
LIst after conversion [21, 10, 14, 11]
Q3
Create a function showEmployee() in such a way that it should accept employee
name, and it’s salary and display both, and if the salary is missing in
function call it should show it as 9000
'''
def showEmployee(name,salary=9000):
print("employee name",name)
print("salary of employee",salary)
n=input("enter employee name")
#s=eval(input("enter employee's salary"))
#showEmployee(n,s)
showEmployee(n)
'''
OUTPUT
enter employee namejohn miller
enter employee's salary6700
employee name john miller
salary of employee 6700
enter employee namesamantha
employee name samantha
salary of employee 9000
'''
Q4
Write a program using function which accept two integers as an argument and
return its sum.Call this function and print the results in main( )
def fun(a,b):
return a+b
a=int(input("enter no1: "))
b=int(input("enter no2: "))
print("sum of 2 nos is",fun(a,b))
'''
OUTPUT
enter no1: 34
enter no2: 43
sum of 2 nos is 77
'''
Q5
Write a definition for function Itemadd () to insert record into the binary file ITEMS.DAT,
(items.dat- id,gift,cost). info should stored in the form of list.
import pickle
def itemadd ():
f=open("items.dat","wb")
n=int(input("enter how many records"))
for i in range(n):
r=int(input('enter id'))
n=input("enter gift name")
p=float(input("enter cost"))
v=[r,n,p]
pickle.dump(v,f)
print("record added")
f.close()
itemadd() #function calling
'''
output
enter how many records2
enter id1
enter gift namepencil
enter cost45
record added
enter id2
enter gift namepen
enter cost120
record added
'''
Q6
Write a definition for function SHOWINFO() to read each record of a binary file
ITEMS.DAT,
(items.dat- id,gift,cost).Assume that info is stored in the form of list
#Sol:
import pickle
def SHOWINFO():
f=open("items.dat","rb")
while True:
try:
g=pickle.load(f)
print(g)
except:
break
f.close()
SHOWINFO()#function calling
'''
output
[1, 'pencil', 45.0]
[2, 'pen', 120.0]
'''
Q7
Write a definition for function COSTLY() to read each record of a binary file
ITEMS.DAT, find and display those items, which are priced less than 50.
(items.dat- id,gift,cost).Assume that info is stored in the form of list
#sol
import pickle
def COSTLY():
f=open("items.dat","rb")
while True:
try:
g=pickle.load(f)
if(g[2]>50):
print(g)
except:
break
f.close()
COSTLY() #function calling
'''
output
[2, 'pen', 120.0]
'''
Q8
A csv file counties.csv contains data in the following order:
country,capital,code
sample of counties.csv is given below:
india,newdelhi,ii
us,washington,uu
malaysia,ualaumpur,mm
france,paris,ff
write a python function to read the file counties.csv and display the names of all those
countries whose no of characters in the capital are more than 6.
import csv
def writecsv():
f=open("counties.csv","w")
r=csv.writer(f,lineterminator='n')
r.writerow(['country','capital','code'])
r.writerow(['india','newdelhi','ii'])
r.writerow(['us','washington','uu'])
r.writerow(['malysia','kualaumpur','mm'])
r.writerow(['france','paris','ff'])
def searchcsv():
f=open("counties.csv","r")
r=csv.reader(f)
f=0
for i in r:
if (len(i[1])>6):
print(i[0],i[1])
f+=1
if(f==0):
print("record not found")
writecsv()
searchcsv()
'''
output
india
us
malaysia
'''
Q9
write a python function to find transfer only those records from the file product.csv to another
file "pro1.csv" whose quantity is more than 150. also include the first row with headings
sample of product.csv is given below:
pid,pname,cost,quantity
p1,brush,50,200
p2,toothbrush,120,150
p3,comb,40,300
p4,sheets,100,500
p5,pen,10,250
#solution---------------------------------------------
import csv
def writecsv():
f=open("product.csv","w")
r=csv.writer(f,lineterminator='n')
r.writerow(['pid','pname','cost','qty'])
r.writerow(['p1','brush','50','200'])
r.writerow(['p2','toothbrush','12','150'])
r.writerow(['p3','comb','40','300'])
r.writerow(['p5','pen','10','250'])
def searchcsv():
f=open("product.csv","r")
f1=open("pro1.csv","w")
r=csv.reader(f)
w=csv.writer(f1,lineterminator='n')
g=next(r)
w.writerow(g)
for i in r:
if i[3]>'150':
w.writerow(i)
def readcsv():
f=open("pro1.csv","r")
r=csv.reader(f)
for i in r:
print(i)
writecsv()
searchcsv()
readcsv()
'''
output
['pid', 'pname', 'cost', 'qty']
['p1', 'brush', '50', '200']
['p3', 'comb', '40', '300']
['p5', 'pen', '10', '250']
'''
Q10
write a python function to search and display the record of that product from the file
PRODUCT.CSV which has maximum cost.
sample of product.csv is given below:
pid,pname,cost,quantity
p1,brush,50,200
p2,toothbrush,120,150
p3,comb,40,300
p4,sheets,100,500
p5,pen,10,250
#solution---------------------------------------------
import csv
def writecsv():
f=open("product.csv","w")
r=csv.writer(f,lineterminator='n')
r.writerow(['pid','pname','cost','qty'])
r.writerow(['p1','brush','50','200'])
r.writerow(['p2','toothbrush','120','150'])
r.writerow(['p3','comb','40','300'])
r.writerow(['p5','pen','10','250'])
def searchcsv():
f=open("product.csv","r")
r=csv.reader(f)
next(r)
m=-1
for i in r:
if (int(i[2])>m):
m=int(i[2])
d=i
print(d)
writecsv()
searchcsv()
'''
output
['p2', 'toothbrush', '120', '150']
'''
Q11
#WAP to find no of lines starting with F in firewall.txt
f=open(r"C:UsershpDesktopcsnetworkingfirewall.txt")
c=0
for i in f.readline():
if(i=='F'):
c=c+1
print(c)
‘’’
Output
1
‘’’
Q12
#WAP to find how many 'f' and 's' present in a text file
f=open(r"C:UsersuserDesktopcsnetworkingfirewall.txt")
t=f.read()
c=0
d=0
for i in t:
if(i=='f'):
c=c+1
elif(i=='s'):
d=d+1
print(c,d)
'''
output
18 41
'''
Q13
Write a program that reads character from the keyboard one by one. All lower case
characters get store inside the file LOWER, all upper case characters get stored inside
the file UPPER and all other characters get stored inside OTHERS.
f=open(r"C:UsersuserDesktopcsnetworkingfirewall.txt")
f1=open("lower.txt","a")
f2=open("upper.txt","a")
f3=open("others.txt","a")
r=f.read()
for i in r:
if(i>='a' and i<='z'):
f1.write(i)
elif(i>='A' and i<='Z'):
f2.write(i)
else:
f3.write(i)
f.close()
f1.close()
f2.close()
f3.close()
Q14
#WAP to find how many 'firewall' or 'to' present in a file firewall.txt
f=open(r"C:UsersuserDesktopcsnetworkingfirewall.txt")
t=f.read()
c=0
for i in t.split():
if(i=='firewall')or (i=='is'):
c=c+1
print(c)
'''
output
9
'''
Q15 A linear stack called "List" contain the following information:
a. Roll Number of student
b. Name of student
Write push(List) and POP(List) methods in python to add and remove from the stack.
#Ans.
List=[]
def add(List):
rno=int(input("Enter roll number"))
name=input("Enter name")
item=[rno,name]
List.append(item)
def pop(List):
if len(List)>0:
List.pop()
else:
print("Stack is empty")
def disp(s):
if(s==[]):
print("list is empty")
else:
top=len(s)-1
print(s[top],"---top")
for i in range(top-1,-1,-1):
print(s[i])
#Call add and pop function to verify the code
add(List)
add(List)
disp(List)
pop(List)
disp(List)
'''
output
Enter roll number1
Enter namereena
Enter roll number2
Enter nameteena
[2, 'teena'] ---top
[1, 'reena']
[1, 'reena'] ---top
'''
16.Consider the following table GARMENT and FABRIC, Write SQL commands for the statements (i) to
(iv)
TABLE GARMENT
GCODE DESCRIPTION PRICE FCODE READYDATE
10023 PENCIL SKIRT 1150 F 03 19-DEC-08
10001 FORMAL SHIRT 1250 F 01 12-JAN-08
10012 INFORMAL SHIRT 1550 F 02 06-JUN-08
10024 BABY TOP 750 F 03 07-APR-07
10090 TULIP SKIRT 850 F 02 31-MAR-07
10019 EVENING GOWN 850 F 03 06-JUN-08
10009 INFORMAL PANT 1500 F 02 20-OCT-08
10007 FORMAL PANT 1350 F 01 09-MAR-08
10020 FROCK 850 F 04 09-SEP-07
10089 SLACKS 750 F 03 20-OCT-08
TABLE FABRIC
FCODE TYPE
F 04 POLYSTER
F 02 COTTON
F 03 SILK
F01 TERELENE
(i) To display GCODE and DESCRIPTION of each GARMENT in descending order of GCODE.
(ii) To display the details of all the GARMENT, which have READYDATE in between 08-DEC-07 and
16-JUN-08 (inclusive if both the dates).
(iii) To display the average PRICE of all the GARMENT, which are made up of fabric with FCODE as
F03.
(iv) To display fabric wise highest and lowest price of GARMENT from GARMENT table. (Display
FCODE of each GARMENT along with highest and lowest Price).
Ans . (i) SELECT GCODE, DESCRIPTION
FROM GARMENT ORDER BY GCODE DESC;
(ii) SELECT * FROM GARMENT
WHERE READY DATE BETWEEN ’08-DEC-07’
AND ’16-JUN-08’;
(iii) SELECT AVG (PRICE)
FROM GARMENT WHERE FCODE = ‘F03’;
(iv) SELECT FCODE, MAX (PRICE), MIN (PRICE)
FROM GARMENT GROUP BY FCODE;
Q17. Write SQL commands for (a) to (f) on the basis of Teacher relation given below:
relation Teacher
No. Name Age Department Date of
join
Salary Sex
1. Jugal 34 Computer 10/01/97 12000 M
2. Sharmila 31 History 24/03/98 20000 F
3. Sandeep 32 Maths 12/12/96 30000 M
4. Sangeeta 35 History 01/07/99 40000 F
5. Rakesh 42 Maths 05/09/97 25000 M
6. Shyam 50 History 27/06/98 30000 M
7. Shiv Om 44 Computer 25/02/97 21000 M
8. Shalakha 33 Maths 31/07/97 20000 F
(a) To show all information about the teacher of history department
(b) To list the names of female teacher who are in Hindi department
(c) To list names of all teachers with their date of joining in ascending order.
(d) To display student’s Name, Fee, Age for male teacher only
(e) To count the number of teachers with Age>23.
(f) To inset a new row in the TEACHER table with the following data:
9, “Raja”, 26, “Computer”, {13/05/95}, 2300, “M”
Ans . (a) SELECT * FROM Teacher
WHERE Department = “History”;
(b) SELECT Name FROM Teacher
WHERE Department = “Hindi” and Sex = “F”;
(c) SELECT Name, Dateofjoin
FROM Teacher
ORDER BY Dateofjoin;
(d) (The given query is wrong as no. information about students and fee etc. is available.
The query should actually be
To display teacher’s Name, Salary, Age for male teacher only)
SELECT Name, Salary, Age FROM Teacher
WHERE Age > 23 AND Sex = ‘M’;
(e) SELECT COUNT (*) FROM Teacher
WHERE Age > 23;
(f) INSERT INTO Teacher
VALUES (9, “Raja”, 26, “Computer”, {13/05/95}, 2300, “M”);
Q18.
Write a MySQL-Python connectivity code display ename, empno,designation, sal of those employees whose
salary is more than 3000 from the table emp . Name of the database is “Emgt”
import mysql.connector as m
db=m.connect(host="localhost",user="root",passwd="1234",database="Emgt")
c=db.cursor()
c.execute("select * from emp where sal>3000")
r=c.fetchall()
for i in r:
print(i)
Q19.
Write a MySQL-Python connectivity code increase the salary(sal) by 300 of those employees whose
designation(job) is clerk from the table emp. Name of the database is “Emgt”
import mysql.connector as m
db=m.connect(host="localhost",user="root",passwd="1234",database="Emgt")
c=db.cursor()
c.execute("update emp set sal=sal+300 where job=”clerk”)
db.commit()

More Related Content

PDF
computer science practical.pdf
DOCX
COMPUTER SCIENCE CLASS 12 PRACTICAL FILE
PPTX
ANSHUL RANA - PROGRAM FILE.pptx
DOCX
CBSE Class 12 Computer practical Python Programs and MYSQL
PDF
Computer science sqp
PDF
computer science investigatory project .pdf
DOCX
computer science file (python)
PDF
selfstudys_com_file (4).pdfjsjdcjjsjxjdnxjj
computer science practical.pdf
COMPUTER SCIENCE CLASS 12 PRACTICAL FILE
ANSHUL RANA - PROGRAM FILE.pptx
CBSE Class 12 Computer practical Python Programs and MYSQL
Computer science sqp
computer science investigatory project .pdf
computer science file (python)
selfstudys_com_file (4).pdfjsjdcjjsjxjdnxjj

Similar to Sample-Program-file-with-output-and-index.docx (20)

PDF
CBSE Class 12 Computer Science(083) Sample Question Paper 2020-21
PDF
Raspberry Pi - Lecture 5 Python for Raspberry Pi
PDF
xii cs practicals
PDF
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
PDF
Practical File Grade 12.pdf
PDF
python_lab_manual_final (1).pdf
PDF
PyLecture4 -Python Basics2-
PDF
Class 12 computer sample paper with answers
DOCX
sample practical file 2022-23 aniket choudhary.docx
PPT
2025pylab engineering 2025pylab engineering
PDF
xii cs practicals class 12 computer science.pdf
DOCX
Python Laboratory Programming Manual.docx
PDF
GVKCV Computer Science(083) Pre board sample paper 2 Class 12 (20-21) with so...
PPTX
Python.pptx
PDF
Python cheatsheat.pdf
PPTX
Python and You Series
PDF
python practicals-solution-2019-20-class-xii.pdf
PPTX
GE8151 Problem Solving and Python Programming
PDF
Sample Program file class 11.pdf
PDF
Python.pdf
CBSE Class 12 Computer Science(083) Sample Question Paper 2020-21
Raspberry Pi - Lecture 5 Python for Raspberry Pi
xii cs practicals
solution-of-practicals-class-xii-comp.-sci.-083-2021-22 (1).pdf
Practical File Grade 12.pdf
python_lab_manual_final (1).pdf
PyLecture4 -Python Basics2-
Class 12 computer sample paper with answers
sample practical file 2022-23 aniket choudhary.docx
2025pylab engineering 2025pylab engineering
xii cs practicals class 12 computer science.pdf
Python Laboratory Programming Manual.docx
GVKCV Computer Science(083) Pre board sample paper 2 Class 12 (20-21) with so...
Python.pptx
Python cheatsheat.pdf
Python and You Series
python practicals-solution-2019-20-class-xii.pdf
GE8151 Problem Solving and Python Programming
Sample Program file class 11.pdf
Python.pdf
Ad

Recently uploaded (20)

PPTX
Cell Structure & Organelles in detailed.
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
Classroom Observation Tools for Teachers
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
A systematic review of self-coping strategies used by university students to ...
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Cell Types and Its function , kingdom of life
PPTX
Pharma ospi slides which help in ospi learning
PDF
Complications of Minimal Access Surgery at WLH
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PPTX
Presentation on HIE in infants and its manifestations
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
01-Introduction-to-Information-Management.pdf
PDF
Computing-Curriculum for Schools in Ghana
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
Cell Structure & Organelles in detailed.
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Classroom Observation Tools for Teachers
Final Presentation General Medicine 03-08-2024.pptx
Chinmaya Tiranga quiz Grand Finale.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
A systematic review of self-coping strategies used by university students to ...
Anesthesia in Laparoscopic Surgery in India
Cell Types and Its function , kingdom of life
Pharma ospi slides which help in ospi learning
Complications of Minimal Access Surgery at WLH
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
Presentation on HIE in infants and its manifestations
Microbial diseases, their pathogenesis and prophylaxis
01-Introduction-to-Information-Management.pdf
Computing-Curriculum for Schools in Ghana
STATICS OF THE RIGID BODIES Hibbelers.pdf
human mycosis Human fungal infections are called human mycosis..pptx
Ad

Sample-Program-file-with-output-and-index.docx

  • 1. COMPUTER SCIENCE WITH PYTHON PROGRAM FILE NAME: CLASS: SECTION:
  • 2. INDEX S.NO TOPIC T.SIGN 1 Write the definition of a function Alter(A, N) in python, which should change all the multiples of 5 in the list to 5 and rest of the elements as 0. 2 Write a code in python for a function void Convert ( T, N) , which repositions all the elements of array by shifting each of them to next position and shifting last element to first position. 3 Create a function showEmployee() in such a way that it should accept employee name, and it’s salary and display both, and if the salary is missing in function call it should show it as 9000 4 Write a program using function which accept two integers as an argument and return its sum. Call this function and print the results in main( ) 5 Write a definition for function Itemadd () to insert record into the binary file ITEMS.DAT, (items.dat- id,gift,cost). info should stored in the form of list. 6 Write a definition for function SHOWINFO() to read each record of a binary file ITEMS.DAT, (items.dat- id,gift,cost).Assume that info is stored in the form of list 7 Write a definition for function COSTLY() to read each record of a binary file ITEMS.DAT, find and display those items, which are priced less than 50. (items.dat- id,gift,cost).Assume that info is stored in the form of list 8 A csv file counties.csv contains data in the following order: country,capital,code sample of counties.csv is given below: india,newdelhi,ii us,washington,uu malaysia,ualaumpur,mm france,paris,ff write a python function to read the file counties.csv and display the names of all those countries whose no of characters in the capital are more than 6. 9 write a python function to search and display the record of that product from the file PRODUCT.CSV which has maximum cost. sample of product.csv is given below: pid,pname,cost,quantity p1,brush,50,200 p2,toothbrush,120,150 p3,comb,40,300 p4,sheets,100,500 p5,pen,10,250
  • 3. 10 write a python function to find transfer only those records from the file product.csv to another file "pro1.csv"whose quantity is more than 150. also include the first row with headings sample of product.csv is given below: pid,pname,cost,quantity p1,brush,50,200 p2,toothbrush,120,150 p3,comb,40,300 p4,sheets,100,500 p5,pen,10,250 11 WAP to find no of lines starting with F in firewall.txt 12 WAP to find how many 'f' and 's' present in a text file 13 Write a program that reads character from the keyboard one by one. All lower case characters get store inside the file LOWER, all upper case characters get stored inside the file UPPER and all other characters get stored inside OTHERS. 14 WAP to find how many 'firewall' or 'to' present in a file firewall.txt 15 A linear stack called "List" contain the following information: a. Roll Number of student b. Name of student Write add(List) and pop(List) methods in python to add and remove from the stack. 16 Consider the tables GARMENT and FABRIC, Write SQL commands for the statements (i) to (iv) 17 Write SQL commands for (a) to (f) on the basis of Teacher relation 18 Write a MySQL-Python connectivity code display ename, empno,designation, sal of those employees whose salary is more than 3000 from the table emp . Name of the database is “Emgt” 19 Write a MySQL-Python connectivity code increase the salary(sal) by 300 of those employees whose designation(job) is clerk from the table emp. Name of the database is “Emgt”
  • 4. Q1 Write the definition of a function Alter(A, N) in python, which should change all the multiples of 5 in the list to 5 and rest of the elements as 0. #sol def Alter ( A, N): for i in range(N): if(A[i]%5==0): A[i]=5 else: A[i]=0 print("LIst after Alteration", A) d=[10,14,15,21] print("Original list",d) r=len(d) Alter(d,r) ''' OUTPUT Original list [10, 14, 15, 21] LIst after Alteration [5, 0, 5, 0] '''
  • 5. Q2 Write a code in python for a function void Convert ( T, N) , which repositions all the elements of array by shifting each of them to next position and shifting last element to first position. e.g. if the content of array is 0 1 2 3 10 14 11 21 The changed array content will be: 0 1 2 3 21 10 14 11 sol: def Convert ( T, N): for i in range(N): t=T[N-1] T[N-1]=T[i] T[i]=t print("LIst after conversion", T) d=[10,14,11,21] print("original list",d) r=len(d) Convert(d,r) OUTPUT: original list [10, 14, 11, 21] LIst after conversion [21, 10, 14, 11]
  • 6. Q3 Create a function showEmployee() in such a way that it should accept employee name, and it’s salary and display both, and if the salary is missing in function call it should show it as 9000 ''' def showEmployee(name,salary=9000): print("employee name",name) print("salary of employee",salary) n=input("enter employee name") #s=eval(input("enter employee's salary")) #showEmployee(n,s) showEmployee(n) ''' OUTPUT enter employee namejohn miller enter employee's salary6700 employee name john miller salary of employee 6700 enter employee namesamantha employee name samantha salary of employee 9000 '''
  • 7. Q4 Write a program using function which accept two integers as an argument and return its sum.Call this function and print the results in main( ) def fun(a,b): return a+b a=int(input("enter no1: ")) b=int(input("enter no2: ")) print("sum of 2 nos is",fun(a,b)) ''' OUTPUT enter no1: 34 enter no2: 43 sum of 2 nos is 77 '''
  • 8. Q5 Write a definition for function Itemadd () to insert record into the binary file ITEMS.DAT, (items.dat- id,gift,cost). info should stored in the form of list. import pickle def itemadd (): f=open("items.dat","wb") n=int(input("enter how many records")) for i in range(n): r=int(input('enter id')) n=input("enter gift name") p=float(input("enter cost")) v=[r,n,p] pickle.dump(v,f) print("record added") f.close() itemadd() #function calling ''' output enter how many records2 enter id1 enter gift namepencil enter cost45 record added enter id2 enter gift namepen enter cost120 record added '''
  • 9. Q6 Write a definition for function SHOWINFO() to read each record of a binary file ITEMS.DAT, (items.dat- id,gift,cost).Assume that info is stored in the form of list #Sol: import pickle def SHOWINFO(): f=open("items.dat","rb") while True: try: g=pickle.load(f) print(g) except: break f.close() SHOWINFO()#function calling ''' output [1, 'pencil', 45.0] [2, 'pen', 120.0] '''
  • 10. Q7 Write a definition for function COSTLY() to read each record of a binary file ITEMS.DAT, find and display those items, which are priced less than 50. (items.dat- id,gift,cost).Assume that info is stored in the form of list #sol import pickle def COSTLY(): f=open("items.dat","rb") while True: try: g=pickle.load(f) if(g[2]>50): print(g) except: break f.close() COSTLY() #function calling ''' output [2, 'pen', 120.0] '''
  • 11. Q8 A csv file counties.csv contains data in the following order: country,capital,code sample of counties.csv is given below: india,newdelhi,ii us,washington,uu malaysia,ualaumpur,mm france,paris,ff write a python function to read the file counties.csv and display the names of all those countries whose no of characters in the capital are more than 6. import csv def writecsv(): f=open("counties.csv","w") r=csv.writer(f,lineterminator='n') r.writerow(['country','capital','code']) r.writerow(['india','newdelhi','ii']) r.writerow(['us','washington','uu']) r.writerow(['malysia','kualaumpur','mm']) r.writerow(['france','paris','ff']) def searchcsv(): f=open("counties.csv","r") r=csv.reader(f) f=0 for i in r: if (len(i[1])>6): print(i[0],i[1]) f+=1 if(f==0):
  • 13. Q9 write a python function to find transfer only those records from the file product.csv to another file "pro1.csv" whose quantity is more than 150. also include the first row with headings sample of product.csv is given below: pid,pname,cost,quantity p1,brush,50,200 p2,toothbrush,120,150 p3,comb,40,300 p4,sheets,100,500 p5,pen,10,250 #solution--------------------------------------------- import csv def writecsv(): f=open("product.csv","w") r=csv.writer(f,lineterminator='n') r.writerow(['pid','pname','cost','qty']) r.writerow(['p1','brush','50','200']) r.writerow(['p2','toothbrush','12','150']) r.writerow(['p3','comb','40','300']) r.writerow(['p5','pen','10','250']) def searchcsv(): f=open("product.csv","r") f1=open("pro1.csv","w") r=csv.reader(f) w=csv.writer(f1,lineterminator='n') g=next(r) w.writerow(g) for i in r:
  • 14. if i[3]>'150': w.writerow(i) def readcsv(): f=open("pro1.csv","r") r=csv.reader(f) for i in r: print(i) writecsv() searchcsv() readcsv() ''' output ['pid', 'pname', 'cost', 'qty'] ['p1', 'brush', '50', '200'] ['p3', 'comb', '40', '300'] ['p5', 'pen', '10', '250'] '''
  • 15. Q10 write a python function to search and display the record of that product from the file PRODUCT.CSV which has maximum cost. sample of product.csv is given below: pid,pname,cost,quantity p1,brush,50,200 p2,toothbrush,120,150 p3,comb,40,300 p4,sheets,100,500 p5,pen,10,250 #solution--------------------------------------------- import csv def writecsv(): f=open("product.csv","w") r=csv.writer(f,lineterminator='n') r.writerow(['pid','pname','cost','qty']) r.writerow(['p1','brush','50','200']) r.writerow(['p2','toothbrush','120','150']) r.writerow(['p3','comb','40','300']) r.writerow(['p5','pen','10','250']) def searchcsv(): f=open("product.csv","r") r=csv.reader(f) next(r) m=-1 for i in r: if (int(i[2])>m): m=int(i[2])
  • 17. Q11 #WAP to find no of lines starting with F in firewall.txt f=open(r"C:UsershpDesktopcsnetworkingfirewall.txt") c=0 for i in f.readline(): if(i=='F'): c=c+1 print(c) ‘’’ Output 1 ‘’’
  • 18. Q12 #WAP to find how many 'f' and 's' present in a text file f=open(r"C:UsersuserDesktopcsnetworkingfirewall.txt") t=f.read() c=0 d=0 for i in t: if(i=='f'): c=c+1 elif(i=='s'): d=d+1 print(c,d) ''' output 18 41 '''
  • 19. Q13 Write a program that reads character from the keyboard one by one. All lower case characters get store inside the file LOWER, all upper case characters get stored inside the file UPPER and all other characters get stored inside OTHERS. f=open(r"C:UsersuserDesktopcsnetworkingfirewall.txt") f1=open("lower.txt","a") f2=open("upper.txt","a") f3=open("others.txt","a") r=f.read() for i in r: if(i>='a' and i<='z'): f1.write(i) elif(i>='A' and i<='Z'): f2.write(i) else: f3.write(i) f.close() f1.close() f2.close() f3.close()
  • 20. Q14 #WAP to find how many 'firewall' or 'to' present in a file firewall.txt f=open(r"C:UsersuserDesktopcsnetworkingfirewall.txt") t=f.read() c=0 for i in t.split(): if(i=='firewall')or (i=='is'): c=c+1 print(c) ''' output 9 '''
  • 21. Q15 A linear stack called "List" contain the following information: a. Roll Number of student b. Name of student Write push(List) and POP(List) methods in python to add and remove from the stack. #Ans. List=[] def add(List): rno=int(input("Enter roll number")) name=input("Enter name") item=[rno,name] List.append(item) def pop(List): if len(List)>0: List.pop() else: print("Stack is empty") def disp(s): if(s==[]): print("list is empty") else: top=len(s)-1 print(s[top],"---top") for i in range(top-1,-1,-1): print(s[i]) #Call add and pop function to verify the code add(List)
  • 22. add(List) disp(List) pop(List) disp(List) ''' output Enter roll number1 Enter namereena Enter roll number2 Enter nameteena [2, 'teena'] ---top [1, 'reena'] [1, 'reena'] ---top '''
  • 23. 16.Consider the following table GARMENT and FABRIC, Write SQL commands for the statements (i) to (iv) TABLE GARMENT GCODE DESCRIPTION PRICE FCODE READYDATE 10023 PENCIL SKIRT 1150 F 03 19-DEC-08 10001 FORMAL SHIRT 1250 F 01 12-JAN-08 10012 INFORMAL SHIRT 1550 F 02 06-JUN-08 10024 BABY TOP 750 F 03 07-APR-07 10090 TULIP SKIRT 850 F 02 31-MAR-07 10019 EVENING GOWN 850 F 03 06-JUN-08 10009 INFORMAL PANT 1500 F 02 20-OCT-08 10007 FORMAL PANT 1350 F 01 09-MAR-08 10020 FROCK 850 F 04 09-SEP-07 10089 SLACKS 750 F 03 20-OCT-08 TABLE FABRIC FCODE TYPE F 04 POLYSTER F 02 COTTON F 03 SILK F01 TERELENE (i) To display GCODE and DESCRIPTION of each GARMENT in descending order of GCODE. (ii) To display the details of all the GARMENT, which have READYDATE in between 08-DEC-07 and 16-JUN-08 (inclusive if both the dates). (iii) To display the average PRICE of all the GARMENT, which are made up of fabric with FCODE as F03. (iv) To display fabric wise highest and lowest price of GARMENT from GARMENT table. (Display FCODE of each GARMENT along with highest and lowest Price). Ans . (i) SELECT GCODE, DESCRIPTION FROM GARMENT ORDER BY GCODE DESC;
  • 24. (ii) SELECT * FROM GARMENT WHERE READY DATE BETWEEN ’08-DEC-07’ AND ’16-JUN-08’; (iii) SELECT AVG (PRICE) FROM GARMENT WHERE FCODE = ‘F03’; (iv) SELECT FCODE, MAX (PRICE), MIN (PRICE) FROM GARMENT GROUP BY FCODE;
  • 25. Q17. Write SQL commands for (a) to (f) on the basis of Teacher relation given below: relation Teacher No. Name Age Department Date of join Salary Sex 1. Jugal 34 Computer 10/01/97 12000 M 2. Sharmila 31 History 24/03/98 20000 F 3. Sandeep 32 Maths 12/12/96 30000 M 4. Sangeeta 35 History 01/07/99 40000 F 5. Rakesh 42 Maths 05/09/97 25000 M 6. Shyam 50 History 27/06/98 30000 M 7. Shiv Om 44 Computer 25/02/97 21000 M 8. Shalakha 33 Maths 31/07/97 20000 F (a) To show all information about the teacher of history department (b) To list the names of female teacher who are in Hindi department (c) To list names of all teachers with their date of joining in ascending order. (d) To display student’s Name, Fee, Age for male teacher only (e) To count the number of teachers with Age>23. (f) To inset a new row in the TEACHER table with the following data: 9, “Raja”, 26, “Computer”, {13/05/95}, 2300, “M” Ans . (a) SELECT * FROM Teacher WHERE Department = “History”; (b) SELECT Name FROM Teacher WHERE Department = “Hindi” and Sex = “F”; (c) SELECT Name, Dateofjoin FROM Teacher ORDER BY Dateofjoin; (d) (The given query is wrong as no. information about students and fee etc. is available. The query should actually be To display teacher’s Name, Salary, Age for male teacher only) SELECT Name, Salary, Age FROM Teacher WHERE Age > 23 AND Sex = ‘M’; (e) SELECT COUNT (*) FROM Teacher WHERE Age > 23; (f) INSERT INTO Teacher VALUES (9, “Raja”, 26, “Computer”, {13/05/95}, 2300, “M”);
  • 26. Q18. Write a MySQL-Python connectivity code display ename, empno,designation, sal of those employees whose salary is more than 3000 from the table emp . Name of the database is “Emgt” import mysql.connector as m db=m.connect(host="localhost",user="root",passwd="1234",database="Emgt") c=db.cursor() c.execute("select * from emp where sal>3000") r=c.fetchall() for i in r: print(i)
  • 27. Q19. Write a MySQL-Python connectivity code increase the salary(sal) by 300 of those employees whose designation(job) is clerk from the table emp. Name of the database is “Emgt” import mysql.connector as m db=m.connect(host="localhost",user="root",passwd="1234",database="Emgt") c=db.cursor() c.execute("update emp set sal=sal+300 where job=”clerk”) db.commit()