You are on page 1of 46

VEER SAVARKAR SARVODAYA KANYA

VIDYALAYA

Computer Science

PRACTICAL FILE

NAME: SOMYA PACHAURI


CLASS: XII(A)
ROLL NO.:60
STUDENT ID:20210406536

` 1

CERTIFICATE:

This is to certify that Somya Pachauri of class 12(A) has


successfully completed the practical work of computer
science for class XII practical examination of the school
2022-23.It is further certified that this practical is the
individual work of the candidate.
SUBMITTED BY: SOMYA PACHAURI

This is to certify that the above statement made by the candidate


is correct and true to the best of my knowledge.

EXAMINER’S SIGNATURE Ms. PURNIMA KHURANA

LECTURER COMPUTER SCIENCE

VSSKV NO.1 KALKAJI

` 2
CONTENT

Sno. Questions Page no.

Write a function LEXCHANGE (Input) in Python, which accepts a 5-6


1. list Input.Function will replace element at odd position with even
position elements.
2. Write a menu driven program to perform different operations on a 6-8
stack.
3. Write a python program to input details of n students from user and store in 9
a binary file.

4. Write a python function rev (Inp) to reverse elements of an Input list Inp 10-11

5. Write a python program to read contents of a text file and display number of 11-12
vowels, consonants, uppercase and lowercase characters in a file.

6. Write a python program to count those dictionary positions that 13-14


equals key or value.

7. Remove all the lines that contain the character 'a' in a file and write it to 14-15
another file

8. Write a Python program to read specific columns of a given CSV file and 16-17
print the content of the columns.

9. Create a binary file with name and roll number. Search for a given roll 17-21
number and display the name, if not found display appropriate message.

10. Write a random number generator that generates random numbers between 22-23
1 and 6 (simulates a dice).

11. Write a program to store employee information entered by user in a 23-24


dictionary.

12. Write a function in Python ADD (Arr), where Arr is a list of numbers. 24-25
From this list push all numbers divisible by 5 into a stack implemented by
using a list. Display the stack if it has at least one element, otherwise
display appropriate error message.

` 3
Sno. Questions Page no.

. Write a function RShift( Input) in Python, which accepts a list of numbers 26-27
13. and shift all elements of list to one position right

14. Take a sample of ten phishing e-mails (or any text file) and find most 27-28
commonly occurring word(s).

15. Write a python program to create table employee (first name, last name, 29-30
age, sex, income) in MySQL using database connectivity.

16. Write a menu driven program in python to implement database connectivity 31-35
Write input, delete, update and show record function with help of any
suitable example.

17. Write a function manipulate (Inp) in Python, which accepts a list Inp of 36-37
numbers The function s performs following manipulations: The elements
which are multiple of 3 are divided by 3 and elements which are multiple of
5 are doubled.
18. Write a function in python square cube (Inp) in Python, which accepts a list 38-39
Inp of numbers and turn first half elements of the list into its square and
second half of thelist into its cube

19. Write a python program that removes all the occurrences of user entered 39-40
element from list and generates a new list.

20. A binary file Book.dat has a structure [book_no, name, Author, price]. 41-42
Write a function CountRec(Author) in Python which accepts the Author
name as parameter and count and return number of books by the given
Author are stored in the binary file "Book.dat".
21. A. Write SQL commands of the following statements; 43-45
B. Give the output of the following SQL queries :
QUESTION 1:
Write a function LEXCHANGE (Input) in Python, which accepts a list Input.

Function will replace element at odd position with even position elements.

CODE:
def leexchange():

for i in range(0,num-1,2):

first=lst[i]

second=lst[i+1]

lst[i]=second

lst[i+1]=first

print("new list:",lst)

lst=[]

num=int(input("Enter the number of elements:"))

for n in range(num):

numbers=int(input("Enter the number"))

lst.append(numbers)

print("original list:",lst)

leexchange()

` 5
OUTPUT:

QUESTION 2:

Write a menu driven program to perform different operations on a


stack.

CODE:
s=[]

c="y"

while (c=="y"or c=="Y"):

print("1.PUSH")

print("2.POP")

print("3.DISPLAY")

choice=int(input("enter your choice "))

if choice==1:

name=input("enter your name ")

` 6
roll=int(input("enter your roll no"))

std=(name,roll)

s.append(std)

elif choice==2:

if s==[]:

print("stack empty")

else:

name,roll =s.pop()

print("deleted item is :", name,roll)

elif choice==3:

i=len(s)

while i>0:

print(s[i-1])

i=i-1

else:

print("wrong input")

c=input("Do you want to continue or not ")

` 7
OUTPUT:

` 8
QUESTION 3:

Write a python program to input details of n students from user and


store in a binary file.
CODE:
import pickle

s={}

file2=open("student.dat",'wb')

R=int(input("Enter roll number"))

N=input("Enter name")

M=float(input("Enter marks"))

#add read data into dictionary

s['Rollno']=R

s['Name']=N

s['Marks']=M

#write into the file

pickle.dump(s,file2)

file2.close()

OUTPUT:

9
QUESTION 4:

Write a python function rev (Inp) to reverse elements of an Input list Inp

CODE:

def reverse():

for i in range(len(L)):

reversedList.append(L[len(L)-i-1])

print("reversedList",reversedList)

reversedList=[]

L=[]

n=int(input("Enter the no.of elements"))

for i in range(0,n):

ele=int(input("Enter the number"))

L.append(ele)

print("original list",L)

reverse()

` 10
OUTPUT:

QUESTION 5: Write a python program to read contents of a text file


and display number of vowels, consonants, uppercase and lowercase
characters in a file.

CODE:
def cnt():

f=open("test.txt","r")

cont=f.read()

print(cnt)

v=0

lc=0

uc=0

cons=0

for i in cont:

` 11
if(i.islower()):

lc+=1

elif(i.isupper()):

uc+=1

if(i in ['a','e','i','o','u',]):

v+=1

elif(i.isalpha()):

cons+=1

f.close()

print("vowels=",v)

print("consonants=",cons)

print("lowercase=",lc)

print("uppercase=",uc)

cnt()

OUTPUT:

` 12
QUESTION 6:

Write a python program to count those dictionary positions that


equals key or value.

CODE:
n=int(input("enter no. of dict element"))

d=dict()

for i in range(n):

key=int(input("enter key"))

value=int(input("enter value"))

d[key]=value

n=len(d)

count=0

ele=int(input("enter the element to be searched:"))

d=list(d.items())

print(d)

for i in range (0,n):

if(ele==d[i][0] or ele==d[i][1]):

count+=1

print("FREQUENCY:", count)

` 13
OUTPUT:

QUESTION 7:

Remove all the lines that contain the character 'a' in a file and write it to
another file.

CODE:
def remove():

fo=open(file1,"r")

fn=open(file2,"w")

l=[]

lines=fo.readlines()

for line in lines:

if 'a' in line:

fn.write(line)

else:

l.append(line)

fo=open(file1,"w")

fo.writelines(l)
` 14
fo.close()

fn.close()

file1=input("Enter the old file name")

file2=input("Enter the new file name")

remove()

OUTPUT:

QUESTION 8:
Write a Python program to read specific columns of a given CSV file and
print the content of the columns.

` 15
CODE:
import csv

def write():

f=open("departments.csv","w",newline='')

wrt=csv.writer(f)

wrt.writerow(["Department_ID","Department_Name","Manager_ID"])

while True:

d_id=int(input("Enter department id:"))

d_name=input("Enter department name: ")

m_id=int(input("Enter manager id: "))

data=[d_id,d_name,m_id]

wrt.writerow(data)

ch=input("Do you want to enter more records(Y/N:)")

if ch in 'Nn':

break

f.close()

def read():

f=open("departments.csv","r",newline='\r\n')

s_reader=csv.reader(f)

for i in s_reader:

print(i)

write()

read()

` 16
OUTPUT:

QUESTION 9:

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.

`17
CODE:
import pickle

def Writerecord(sroll,sname):

with open ('Student.dat','ab') as Myfile:

srecord={"SROLL":sroll,"SNAME":sname}

pickle.dump(srecord,Myfile)

def Readrecord():

with open ('Student.dat','rb') as Myfile:

print("\n-------DISPALY STUDENTS DETAILS--------")

print("\nRoll No.",' ','Name','\t',end='')

print()

while True:

try:

rec=pickle.load(Myfile)

print(' ',rec['SROLL'],'\t ' ,rec['SNAME'])

except EOFError:

break

def Input():

n=int(input("How many records you want to create :"))

for ctr in range(n):

` 18
sroll=int(input("Enter Roll No: "))

sname=input("Enter Name: ")

Writerecord(sroll,sname)

def SearchRecord(roll):

with open ('Student.dat','rb') as Myfile:

while True:

try:

rec=pickle.load(Myfile)

if rec['SROLL']==roll:

print("Roll NO:",rec['SROLL'])

print("Name:",rec['SNAME'])

except EOFError:

print("Record not find..............")

print("Try Again..............")

break

def main():

while True:

print('\nYour Choices are: ')

` 19
print('1.Insert Records')

print('2.Dispaly Records')

print('3.Search Records (By Roll No)')

print('0.Exit (Enter 0 to exit)')

ch=int(input('Enter Your Choice: '))

if ch==1:

Input()

elif ch==2:

Readrecord()

elif ch==3:

r=int(input("Enter a Rollno to be Search: "))

SearchRecord(r)

else:

break

main()

` 20
OUTPUT:

` 21
QUESTION 10:

Write a random number generator that generates random numbers


between 1 and 6 (simulates a dice).
CODE:
import random

def rolladice():

counter = 0

myList = []

while (counter) < 6:

randomNumber = random.randint(1,6)

myList.append(randomNumber)

counter = counter + 1

if (counter)>=6:

pass

else:

return myList

n=1

while(n==1):

n = int(input("Enter 1 to roll a dice and get a random number:"))

print(rolladice())

` 22
OUTPUT:

QUESTION 11:

Write a program to store employee information entered by user in a


dictionary.
CODE:

emp_dict = { }

while True :

name = input("Enter employee name : ")

sal = int(input("Enter employee salary : "))

emp_dict[ name] = sal

choice = input("Do you want to Enter another record Press 'y' if yes : ")

if choice != "y" :

break

print(emp_dict)

` 23
OUTPUT:

QUESTION 12:

Write a function in Python ADD (Arr), where Arr is a list of


numbers. From this list push all numbers divisible by 5 into a stack
implemented by using a list.Display the stack if it has at least one
element, otherwise display appropriate error message.
CODE:
def PUSH(Arr):

s=[]

for i in range(0,len(Arr)):

if Arr[i]%5==0:

s.append(Arr[i])

if len(s)==0:

` 24
print("Stack is empty")

else:

print(s)

Arr =[]

n=int(input("Enter no. of element"))

for i in range(0,n):

ele=int(input("Enter element:"))

Arr.append(ele)

print(Arr)

ADD(Arr)

OUTPUT:

` 25
QUESTION 13:

Write a function RShift( Input) in Python, which accepts a


list of numbers and shift all elements of list to one position
right.
CODE:
def RShift(L):

n=len(L)

last=L[n-1]

for i in range(n-2,-1,-1):

L[i+1]=L[i]

L[0]=last

print("modified list is:",

L)

L=[]

n=int(input("Enter the no. of element:"))

for i in range (0,n):

ele=int(input("Enter the elements"))

L.append(ele)

RShift(L)

` 26
OUTPUT:

QUESTION 14:

Take a sample of ten phishing e-mails (or any text file) and find most
commonly occurring word(s).

CODE:
file=open("email2.txt",'r')

content=file.read()

dict={}

words=content.split()

for word in words:

if word in dict:

dict[word]+=1

else:

` 27
dict[word]=1

fin_max=max(dict,key=dict.get)

print("most occuring word",fin_max)

print("Other words frequency is :",dict)

OUTPUT:

` 28
QUESTION 15:

Write a python program to create table employee (first name, last


name, age, sex, income) in MySQL using database connectivity .

CODE:
import mysql.connector

mydb=mysql.connector.connect(host="localhost", user="root",
passwd="mysql", database="real_estate")

mycursor=mydb.cursor()

mycursor.execute("create table employee(first_name varchar(20),\

last_name varchar(20),age integer,income varchar(10))")

mycursor.close()

mydb.close()

OUTPUT:

`29
QUESTION 16:

Write a menu driven program in python to implement database


connectivity .Write input, delete, update and show record function
with help of any suitable example.
CODE:
import mysql.connector

while True:

print("--------CLIENT PROFILE---------")

print("1-Create table")

print("2-Insert details")

print("3-Update details")

print("4-Deletion of records")

print("5-Display details")

print("6-Main menu")

choice=int(input("Enter your choice(1-6)"))

while True:

#TO CREATE TABLE OF CLIENT

if choice==1:

mydb=mysql.connector.connect(host="localhost",

user="root",

passwd="mysql",

database="real_estate")

mycursor=mydb.cursor()

` 30
mycursor.execute ="CREATE TABLE client_detail(Id int(11) PRIMARY KEY NOT
NULL,Name VARCHAR(255), Address VARCHAR(255))"

print("table created successfully")

mydb.close()

break

#TO INSERT RECORD OF CLIENT

elif choice==2:

mydb=mysql.connector.connect(host="localhost",

user="root",passwd="mysql", database="real_estate")

mycursor=mydb.cursor()

id=int(input("Enter client id"))

name=input("Enter client name")

adrs=str(input("Enter address"))

sql="INSERT INTO client_detail(Id,Name,Address)

VALUES({},'{}','{}')". format(id,name,adrs)

mycursor.execute(sql)

print(mycursor.rowcount,"Record inserted successfully")

mydb.commit()

mydb.close()

break

#TO UPDATE DETAILS OF CLIENT

elif choice==3:

mydb=mysql.connector.connect(host="localhost",

user="root",

passwd="mysql",

` 31
database="real_estate")

mycursor=mydb.cursor()

query="UPDATE client_detail SET address='Kolkata' WHERE name='Riy'"

mycursor.execute(query)

mydb.commit()

print("Data updated sccessfully")

break

#TO DELETE DETAILS OF CLIENT

elif choice==4:

mydb=mysql.connector.connect(host="localhost",

user="root", passwd="mysql", database="real_estate")

mycursor=mydb.cursor()

query="DELETE from client_detail WHERE id=1003"

mycursor.execute(query)

mydb.commit()

print("Deletion sccessfully")

break

#TO DISPLAY DETAILS OF CLIENT

elif choice==5:

mydb=mysql.connector.connect(host="localhost",

user="root", passwd="mysql", database="real_estate")

mycursor=mydb.cursor()

query="SELECT*from client_detail"

mycursor.execute(query)
` 32
myrecords=mycursor.fetchall()

print("Id,Name,Address are:")

for x in myrecords:

print (x)

print(mycursor.rowcount,"record selected")

mycursor.close()

mydb.close()

break

else:

print("Error:Invalid choice try again")

break

OUTPUT:

` 33
`34
QUESTION 17:
Write a function manipulate (Inp) in Python, which accepts a list
Inp of numbers .The function is performs following
manipulations:The elements which are multiple of 3 are divided by
3 and elements which are multiple of 5 are doubled.

CODE:
def manipulate ():

for i in range (0,n+1):

if l1[i]%3==0:

l1[i]=l1[i]//3

elif l1[i]%5==0:

l1[i]=l1[i]*2

print("new list is ",l1)

l1 = []

num = int(input("enter the number of elements :" ))

for n in range(num):

numbers = int(input("Enter the number "))

l1.append(numbers)

print("original list: ",l1)

manipulate()

print("END OF FUNCTION")

` 35
OUTPUT:

` 36
QUESTION 18:

Write a function in python square cube (Inp) in Python, which accepts


a list Inp of numbers and turn first half elements of the list into its
square and second half of thelist into its cube.
CODE:

def square_cube(L,n):

h=int(n/2)

for i in range(0,h):

L[i]=L[i]*L[i]

for j in range (h,n):

L[j]=L[j]**3

print("Modified list is:",L)

L=[]

n=int(input("Enter the no.of elements:"))

for i in range(0,n):

ele=int(input("Enter the element:"))

L.append(ele)

square_cube(L,n)

` 37
OUTPUT:

QUESTION 19:

Write a python program that removes all the occurrences of user entered
element from list and generates a new list.

CODE:

L=[]

n=int(input("enter the number of element"))

for i in range(0,n):

ele=int(input("enter the element:"))

L.append(ele)

print(L)

x=int(input("enter the element to be removed :"))

for i in L:

` 38
if i==x:

L.remove(x)

print(L)

OUTPUT:

QUESTION 20:

A binary file Book.dat has a structure [book_no, name, Author,


price]. Write a function CountRec(Author) in Python which accepts
the Author name as parameter and count and return number of
books by the given Author are stored in the binary file "Book.dat".
CODE :

import pickle as p

def Createfile():

BookNo=int(input("Enter Book No:"))

Book_Name=input("Enter Book Name:")

Author=input("Enter Author:")

Price=float(input("Enter Price"))

l=[BookNo,Book_Name,Author,Price]

f=open("Book.dat","ab")

` 39
p.dump(l,f)

f.close()

def Countrec(Author):

count=0

f=open("Book.dat","rb")

while True:

try:

l=p.load(f)

if l[2]==Author:

count=count+1

except EOFError:

print("EOF reached")

break

return count

OUTPUT:

` 40
QUESTION 21:
Consider the tables EMPLOYEE and SALGRADE given below and
answer (a) and (b) parts of this question.

TABLE : EMPLOYEE

ECODE NAME DESIG SGRADE DOJ DOB


101 Abdul ahmad Executive S03 2003-03-23 1980-01-13
102 Ravi chander Head IT S02 2010-02-12 1987-06-22
103 John ken Receptionist S03 2009-06-24 1983-02-24
105 Nazar amen GM S02 2006-08-11 1984-03-03
108 Priyam sen CEO S01 2004-12-29 1982-01-19

TABLE: SGRADE

SGRADE SALARY HRA


S01 56000 18000
S02 32000 12000
S03 24000 8000

` 41
TABLE : EMPLOYEE AND SALGRADE

` 42
(a) Write SQL commands of the following statements;
(i) To display the details of all EMPLOYEE in descending order of DOJ.
ANS. SELECT * FROM EMPLOYEE ORDER BY DOJ DESC;

(ii) To display NAME and DESIGN of those EMPLOYEES, whose SAL-


GRADE is either S02 or S03.

ANS. SELECT NAME , DESIG FROM EMPLOYEEWHERE


SGRADE=’S02’OR SGRADE=’S03’

(iii) To display the content of all the EMPLOYEES table, whose DOJ is in
between ’09-Feb-2006′ and ’08-Aug-2009

ANS. SELECT*FROM EMPLOYEE WHERE DOJ BETWEEN


‘2006-02-09’ AND ‘2009-08-02’;

` 43
(iv) To add a new row with the following: 109, ‘HarishRoy’, ‘HEAD-IT’,
‘SOX, ’09-Sep-2007′, ’21-Apr-1983’

ANS. INSERT INTO EMPLOYEE VALUES 9109,’Harish Roy’, ’HEAD-IT’


,’S02’,‘2007-09-09’ , ‘1983-04-21’);

(v) To display HRA of employees who were born after in year 1982 or 1987
ANS. SELECT HRA FROM EMPLOYEE WHOSE DOB BETWEEN ‘1982-
01-19’and 1987-06-22’

(vi) Display name, designation, salary and HRA of employees who have letter
'a' in their names.

ANS. SELECT NAME, DESIG, SALARY AND HRA FROM EMPLOYEE,


SALGRADE WHERE EMPLOYEE.SALGRADE=SALGRADE.SGRADE
AND WHERE NAME LIKE ’%a%’;

` 44
(b)Give the output of the following SQL queries :
(i)SELECT COUNT(SGRADE), SGRADE FROM EMPLOYEE
GROUP BY SGRADE;

OUTPUT:

COUNT(SGRADE) SGRADE
2 S03
2 S02
1 S01

(ii) SELECT MIN(DOB), MAX(DOJ) FROM EMPLOYEE;


OUTPUT:

MIN(DOB) MAX(DOJ)
1980-01-13 2010-02-12

(iii) SELECT NAME, SALARY FROM EMPLOYEE E, SAL-GRADE S


WHERE E.SGRADE= S.SGRADE AND E.ECODE<103′;

OUTPUT:

SGRADE SALARY+HRA
S02 44000

` 45

You might also like