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

COMPUTER PRACTICAL FILE 2

The document contains a list of programming tasks, each with a brief description of the required functionality, such as displaying frequencies of list elements, summing values ending with a specific digit, and handling file operations. It includes various programming challenges that cover topics like data structures, file handling, and database connectivity. Each task is presented with a sample code snippet and expected output.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views44 pages

COMPUTER PRACTICAL FILE 2

The document contains a list of programming tasks, each with a brief description of the required functionality, such as displaying frequencies of list elements, summing values ending with a specific digit, and handling file operations. It includes various programming challenges that cover topics like data structures, file handling, and database connectivity. Each task is presented with a sample code snippet and expected output.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

INDEX

S No. PROGRAM SIGN


1 Write a program to display frequencies of all the element of a list.

2 Write a program to find and display the sum of all the values which
are ending with 8 from a list.

3 Write a Program to show the sum of diagonal (major and minor) of a


2-d list.

4 Write a program to input name of ‘n’ countries and their capital and
currency store, it in a dictionary and display in tabular form also
search and display for a particular country.

5 Write a program to show all prime numbers in the entered range .

6 Write a program to show sorting of elements of a list step-by-step.

7 Write a program to read data from a text file DATA.TXT, and


display each words with number of vowels and consonants.

8 Using “coordinate.txt” file create a python function to count the


number of words having first character capital.

9 Write a program that reads character from the file keyboard.txt 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.

10 Write a program to insert record into the binary file ITEMS.DAT,


(items.dat- id,gift,cost). info should stored in the form of list.

11 Write a program) 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).info is stored in the form of list.

12 Write a program that will write a string in binary file "school.dat" and
display the words of the string in reverse order.

13 Write a program to insert list data in CSV File and print it.
14 Write a python function readcsv () to display the information from
product.csv. Following info is also to be added in the file prior to
printing.
pid,pname,cost,quantity

15 Write a program to insert item on selected position in list and print


the updated list.

16 Write a program to show push and pop operation using stack.

17 Create a table with under mentioned structure (Table name is EMP)


EMPNo NUMBER(4)
DeptNo NUMBER(2)
EmpName CHAR(10)
Job CHAR(10)
Manager NUMBER(4)
Hiredate DATE
Salary NUMBER(7,2)
Commission NUMBER(7,2)

18
Table: EMPLOYEE
EMPLOYEEID NAME SALES JOBID
E1 SUMIT SINHA 110000 102
E2 VIJAY SINGH 130000 101
TOMAR
E3 AJYA RAJPAL 125000 103
E4 MOHIT RAMANI 140000 102
E5 SHAILJA SINGH 145000 103

Table: JOB

JOBID JOBTITLE SALARY


101 VICE PRESIDENT 200000
102 ADMINISTRATION 125000
ASSISTANT
103 PRESIDENT 80000
104 ADMINISTRATION 70000
105 ACCOUNTANT 65000
a) To display employee ids, names of employees, job ids with
corresponding job titles.
b) To display names of employees,sales and corresponding job
titles who have achieved sales more than 130000.
c) To display names and corresponding job titles of those
employees who have ‘SINGH’(anywhere) in their names.

19 Write a program to show MySQL CONNECTIVITY for inserting


two tuples in table:"student" inside database:"class12"

20 Write SQL commands.


Table: GRADUATE
S.NO. NAME STIPEND SUBJECT AVERAGE DIVISION
1 KARAN 400 PHYSICS 68 1
2 DIVAKAR 450 COMPUTER SC 68 1
3 DIVYA 300 CHEMISTRY 62 2
4 ARUN 350 PHYSICS 63 1
5 SABINA 500 MATHEMATICS 70 1
6 JOHN 400 CHEMISTRY 55 2
7 ROBERT 250 PHYSICS 64 1
8 RUBINA 450 MATHEMATICS 68 1
9 VIKAS 500 COMPUTER SC 62 1
10. MOHAN 300 MATHEMATICS 57 2

1. List the names of those students who have obtained DIV 1


sorted by NAME.
2. Display a report, listing NAME, STIPEND, SUBJECT and
amount of stipend received in a year assuming that the
STIPEND is paid every month.
3. To count the number of students who are either PHYSICS or
COMPUTER SC graduates.
4. To insert a new row in the GRADUATE table:
11, “KAJOL”, 300, “COMPUTER SC”, 75, 1
5. To display the names of all students whose name starts with
“A”
6. To change the subject to “PHYSICS” of all students whose
stipend is more than 400
7. Increase the stipend of all students by 500
PROGRAM 1
Write a program to display frequencies of all the elements of a list.

L=[11, 21, 54, 32, 11, 54, 6, 7, 21, 6]


L1=[]
L2=[]
for i in L:
if i not in L2:
x=L.count(i)
L1.append(x)
L2.append(i)
print('Element','\t\t\t',"Frequency")
for i in range (len(L1)):
print(L2[i],'\t\t\t',L1[i])

OUTPUT
PROGRAM 2
Write a program to find and display the sum of all the values which are
ending with 8 from a list.

L=[12, 48, 21, 24, 40, 11, 98, 99]


sum=0
x=len(L)
for i in range(0,x):
if type(L[i])==int:
if L[i]%10==8:
sum+=L[i]
print(sum)

OUTPUT
PROGRAM 3
Write a Program to show the sum of diagonal (major and minor) of a 2-d list.

r=int(input("Enter Number of Rows : "))


c=int(input("Enter Number of Columns : "))
mylist=[]
for i in range(0, r):
mylist.append([])
for i in range(0, r):
for j in range(0, c):
mylist[i].append(j)
# mylist[i][j]=0
for i in range(0, r):
for j in range(0, c):
print("Enter Value : ")
mylist[i][j]=int(input())
for i in range(0, r):
for j in range(0, c):
print (mylist[i][j], end=' ')
print("\n")
sumd1=0
sumd2=0
j=c-1
print("Sum of Diagonals (major and minor) in Two Dimensional List: ")
for i in range(0,r):
sumd1=sumd1+mylist[i][i]
sumd2=sumd2+mylist[i][j]
j=j-1
print ("The sum of diagonal 1 is : ", sumd1)
print ("The sum of diagonal 2 is : ", sumd2)

OUTPUT
PROGRAM 4
Write a program to input the name of ‘n’ countries and their capital and
currency store, it in a dictionary and display in tabular form also search and
display for a particular country.

d1=dict(), i=1
n=int(input("enter number of entries"))
while i<=n:
c=input("enter country:")
cap=input("enter capital:")
curr=input("enter currency of country")
d1[c]=[cap,curr]
i=i+1
l=d1.keys()
print("\ncountry\t\t","capital\t\t","currency")
for i in l:
z=d1[i]
print(i,'\t\t',end=" ")
for j in z:
print(j,'\t\t',end='\t\t')
x=input("\nenter country to be searched:") #searching
for i in l:
if i==x:
print("\ncountry\t\t","capital\t\t","currency\t\t")
z=d1[i]
print(i,'\t\t',end=" ")
for j in z:
print(j,'\t\t',end="\t")
break
OUTPUT
PROGRAM 5
Write a program to show all prime numbers in the entered range.

def prm(l,u):
for i in range(l, u+1):
for j in range(2, i):
a=i%j
if a==0:
break
if a!=0:
print(i)
l=int(input("Enter lower limit: "))
u=int(input("Enter upper limit: "))
prm(l, u)
PROGRAM 6
Write a program to show sorting of elements of a list step-by-step.

a=[23, 12, 45, 54, 11, 10, 1, 67]


print("the unsorted list is ",a)
print("the sorting starts now:")
n=len(a)
for i in range(n):
for j in range(0,n-i-1):
if a[j]>a[j+1]:
a[j],a[j+1]=a[j+1],a[j]
print("the list after sorting " , i ,"loop is",a)
print("the list after sorting is",a)

OUTPUT
PROGRAM 7
Write a program to read data from a text file DATA.TXT, and display each
word with a number of vowels and consonants.

f1=open("data.txt","r")
s=f1.read()
print(s)
countV=0
countC=0
words=s.split()
print(words,", ",len(words))
for word in words:
countV=0
countC=0
for ch in word:
if ch.isalnum()==True:
if ch=='a' or ch=='e' or ch=='i' or ch=='o' or ch=='u':
countV+=1
else:
countC+=1
print("Word : ",word,", V: ",countV,", C= ", countC)

OUTPUT
PROGRAM 8
Using “coordinate.txt” file, create a python function to count the number of
words having first character capital.

f1=open("coordinate.txt", "r")
t=f1.read()
c=0
for i in t.split():
if i.istitle() :
c=c+1
print("Data in file, \n", t)
print(c, " is the no. of reqd words.")

OUTPUT
PROGRAM 9
Write a program that reads character from the file keyboard.txt 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("keyboard.txt", "r")
f1=open("LOWER.txt", "w")
f2=open("UPPER.txt", "w")
f3=open("OTHERS.txt", "w")
t=f.read()
for i in t:
if i.islower() :
f1.write(i)
elif i.isupper():
f2.write(i)
else:
f3.write(i)
f1.close()
f2.close()
f3.close()
f.close()
f1=open("LOWER.txt", "r")
f2=open("UPPER.txt", "r")
f3=open("OTHERS.txt", "r")
print("Contents of LOWER.txt \n", f1.read())
print("\nContents of UPPER.txt \n", f2.read())
print("\nContents of OTHER.txt \n", f3.read())
f1.close()
f2.close()
f3.close()
OUTPUT
PROGRAM 10
Write a program to insert record into the binary file ITEMS.DAT,
(items.dat- id,gift,cost). info should be stored in the form of a list.

import pickle
f=open("items.dat", "ab")
n=input("Enter Id ")
g=input("Enter Gift ")
c=int(input("Enter Cost "))
l=[n, g, c]
pickle.dump(l, f)
f.close()
f1=open("items.dat", "rb") #reading
while True:
try:
r=pickle.load(f1)
print(r)
except:
break
f1.close()

OUTPUT
PROGRAM 11
Write a program) 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).info
is stored in the form of list

import pickle
f1=open("items.dat", "rb") #reading
while True:
try:
r=pickle.load(f1)
if r[2]<50:
print(r)
except:
break
f1.close()

OUTPUT
PROGRAM 12
Write a program that will write a string in binary file "school.dat" and
display the words of the string in reverse order.

import pickle
str="Computer Science is The Most Fascinating subject of All. "
f1=open('school.dat','wb')
pickle.dump(str,f1)
print("the string is written in the ",f1.name, "file")
f1.close()

f1=open('school.dat','rb')
str1=pickle.load(f1)
print("\n\nThe string in the binary file is : \n",str1)
str1=str1.split(" ")
l=list(str1)
print("\nthe list is ",l, "\n")
l.reverse()
print("The REVERSE IS \n",l )

OUTPUT
PROGRAM 13
Write a program to insert list data in CSV File and print it.

import csv
fields = ['Name', 'Branch', 'Year', 'CGPA']
rows = [ ['Anill', 'COE', '2', '9.0'],
['Sanchit', 'COE', '2', '9.1'],
['Adit', 'IT', '2', '9.3'],
['Sagarika', 'SE', '1', '9.5'],
['Prachi', 'MCE', '3', '7.8'],
['Salim', 'EP', '2', '9.1']]
filename = "MYCSV.csv"
with open(filename, 'w') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(fields)
csvwriter.writerows(rows)
with open('MYCSV.csv', newline='') as File:
reader = csv.reader(File)
for row in reader:
print(row)

OUTPUT
PROGRAM 14
Write a python function readcsv () to display the information from
product.csv. Following info is also to be added in the file prior to printing.
pid,pname,cost,quantity

import csv
fields = ['pid', 'pname', 'cost', 'quantity']
rows = [ ['1', 'Pen', '100', '401'],
['2', 'Notebook', '40', '356'],
['3', 'Tablet', '20000', '101'],
['4', 'Bottle', '99', '400'],
['5', 'Solomon', '600', '12']]
filename="product.csv"
with open(filename, 'w') as csvfile: #entering data
csvwriter = csv.writer(csvfile)
csvwriter.writerow(fields)
csvwriter.writerows(rows)
with open('product.csv', newline='') as File: #printing
reader = csv.reader(File)
for row in reader:
print(row)

OUTPUT
PROGRAM 15
Write a program to insert item on selected position in list and print the
updated list.

n=int(input("Enter Number of items in List: "))


DATA=[]
for i in range(n):
item=int(input("Item :%d: "%(i+1)))
DATA.append(item)
print("Now List Items are :",DATA)
print("Now Number of items before update are :",len(DATA))
e=int(input("Enter Item = "))
pos=int(input("Enter POS = "))
DATA.append(None)
le=len(DATA)
for i in range(le-1,pos-1,-1):
DATA[i]=DATA[i-1]
print("Now List Items are :",DATA)
DATA[pos-1]=e
print("Now Number of items are :",len(DATA))
print("Now Updated List Items are :",DATA)

OUTPUT
PROGRAM 16
Write a program to sort a list of items using BUBBLE SORT.

import time
n=int(input("Enter Number of items in List: "))
DATA=[]
for i in range(n):
item=int(input("Item :%d: "%(i+1)))
DATA.append(item)
print("Array Before Sorted : ",DATA)
for i in range(1,len(DATA)):
print("*****************(%d)*************************"%i)
c=1
for j in range(0,len(DATA)-i):
if(DATA[j]>DATA[j+1]):
DATA[j],DATA[j+1] = DATA[j+1],DATA[j]
time.sleep(0.200)
print("%2d"%c,":",DATA)
c+=1
print("%2d"%i,":",DATA)
time.sleep(0.900)
print("Array After Sorted : ",DATA)
OUTPUT
PROGRAM 17
Write a program to show push and pop operation using stack.

def push(stack,x): #function to add element at the end of list


stack.append(x)
def pop(stack): #function to remove last element from list
n = len(stack)
if(n<=0):
print("Stack empty....Pop not possible")
else:
stack.pop()
def display(stack): #function to display stack entry
if len(stack)<=0:
print("Stack empty...........Nothing to display")
for i in stack:
print(i,end=" ")
#main program starts from here
x=[]
choice=0
while (choice!=4):
print("\n********Stack Menu***********")
print("1. push(INSERT)")
print("2. pop(DELETE)")
print("3. Display ")
print("4. Exit")
choice = int(input("Enter your choice :"))
if(choice==1):
value = int(input("Enter value "))
push(x,value)
if(choice==2):
pop(x)
if(choice==3):
display(x)
if(choice==4):
print("You selected to close this program")
OUTPUT
PROGRAM 18
Write a program to show insertion and deletion operation using a queue.

def add_element(Queue,x): #function to add element at the end of list


Queue.append(x)

def delete_element(Queue): #function to remove last element from list


n = len(Queue)
if(n<=0):
print("Queue empty....Deletion not possible")
else:
del(Queue[0])

def display(Queue): #function to display Queue entry


if len(Queue)<=0:
print("Queue empty...........Nothing to display")
for i in Queue:
print(i,end=" ")
#main
x=[]
choice=0
while (choice!=4):
print(" ********Queue menu***********")
print("1. Add Element ")
print("2. Delete Element")
print("3. Display ")
print("4. Exit")
choice = int(input("Enter your choice : "))
if(choice==1):
value = int(input("Enter value : "))
add_element(x,value)
if(choice==2):
delete_element(x)
if(choice==3):
display(x)

OUTPUT
PROGRAM 19
Create a table with under mentioned structure (Table name is EMP)
EMPNo NUMBER(4)
DeptNo NUMBER(2)
EmpName CHAR(10)
Job CHAR(10)
Manager NUMBER(4)
Hiredate DATE
Salary NUMBER(7,2)
Commission NUMBER(7,2)

import mysql.connector as m
db=m.connect(host="localhost",user="root",passwd="1234",database="edu")
c=db.cursor()
c.execute("CREATE TABLE EMP(EMPNO numeric(4), DeptNo numeric(2),
EmpName char(10), Job char(10), Manager numeric(4), Hiredate Date, Salary
numeric(7, 2), Commission numeric(7, 2))")

c.execute("desc EMP")
for i in c:
print(i)

OUTPUT
PROGRAM 20

Table: EMPLOYEE
EMPLOYEEID NAME SALES JOBID
E1 SUMIT SINHA 110000 102
E2 VIJAY SINGH 130000 101
TOMAR
E3 AJYA RAJPAL 125000 103
E4 MOHIT RAMANI 140000 102
E5 SHAILJA SINGH 145000 103

Table: JOB
JOBID JOBTITLE SALARY
101 VICE PRESIDENT 200000
102 ADMINISTRATION 125000
ASSISTANT
103 PRESIDENT 80000
104 ADMINISTRATION 70000
105 ACCOUNTANT 65000
a) To display employee ids, names of employees, job ids with corresponding job titles.
b) To display names of employees,sales and corresponding job titles who have achieved sales
more than 130000.
c) To display names and corresponding job titles of those employees who have
‘SINGH’(anywhere) in their names.

import mysql.connector as m
db=m.connect(host="localhost",user="root",passwd="1234",database="edu")
c=db.cursor()
c.execute("select EMPLOYEEID, NAME, employee.JOBID, JOBTITLE from
employee, job where employee.JOBID=job.JOBID") #a
for i in c:
print(i)
print("\n\n\n")
c.execute("select NAME, SALES, JOBTITLE from employee, job where
employee.JOBID=job.JOBID and SALES>130000") #b
for i in c:
print(i)
print("\n\n\n")
c.execute("select NAME, JOBTITLE from employee, job where
employee.JOBID=job.JOBID and NAME like '%SINGH%'") #c
for i in c:
print(i)

OUTPUT

PROGRAM 21
Write a program to show MySQL CONNECTIVITY for inserting two tuples
in table:"student" inside database:"class12"
import mysql.connector as m

db=m.connect(host="localhost",user="root",passwd="1234",database="edu")

c=db.cursor()

c.execute("INSERT INTO student(admno,name,class,sec,rno,address)


VALUES({},'{}','{}','{}',{},'{}')".format(1236,"Nitin",11,'a',43,"Gurugram"))

c.execute("INSERT INTO
student(admno,name,class,sec,rno,address)VALUES({},'{}','{}','{}',{},'{}')".format(1237
,"Mukesh",12,'c',3,"Narayana"))

db.commit()

print("record inserted")

c.execute("select * from student")

data=c.fetchall()

for row in data:

print(row)

OUTPUT
PROGRAM 22
Write SQL commands.
Table: GRADUATE
S.NO. NAME STIPEND SUBJECT AVERAGE DIVISION
1 KARAN 400 PHYSICS 68 1
2 DIVAKAR 450 COMPUTER SC 68 1
3 DIVYA 300 CHEMISTRY 62 2
4 ARUN 350 PHYSICS 63 1
5 SABINA 500 MATHEMATICS 70 1
6 JOHN 400 CHEMISTRY 55 2
7 ROBERT 250 PHYSICS 64 1
8 RUBINA 450 MATHEMATICS 68 1
9 VIKAS 500 COMPUTER SC 62 1
10. MOHAN 300 MATHEMATICS 57 2

1. List the names of those students who have obtained DIVISION 1 sorted
by NAME.
2. Display a report, listing NAME, STIPEND, SUBJECT and amount of
stipend received in a year assuming that the STIPEND is paid every
month.
3. To count the number of students who are either PHYSICS or
COMPUTER SC graduates.
4. To insert a new row in the GRADUATE table:
11, “KAJOL”, 300, “COMPUTER SC”, 75, 1
5. To display the names of all students whose name starts with “A”
6. To change the subject to “PHYSICS” of all students whose stipend is
more than 400
7. Increase the stipend of all students by 500

import mysql.connector as m
db=m.connect(host="localhost",user="root",passwd="1234",database="edu",
buffered=True)
c=db.cursor()
c.execute("select NAME from graduate where DIVISION=1 order by NAME") #a
for i in c:
print(i)
print("\n\n")
c.execute("select NAME, STIPEND, SUBJECT, STIPEND*12 as 'ANNUAL STIPEND'
from graduate")#b
for i in c:
print(i)
print("\n\n")
c.execute("select count(*) from graduate where SUBJECT='PHYSICS' or
SUBJECT='COMPUTER SC'")#c
for i in c:
print(i)
print("\n\n")
c.execute("insert into graduate values(11, 'KAJOL', 300, 'COMPUTER SC', 75, 1)")#d
c.execute("select NAME from graduate where NAME like 'A%'")#e
for i in c:
print(i)
print("\n\n")
c.execute("update graduate set SUBJECT='PHYSICS' where STIPEND>400")#f
c.execute("update graduate set STIPEND=STIPEND +500")#g
c.execute("select * from graduate")
for i in c:
print(i)
OUTPUT

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy