Somya - Xii (A) - 60 - CS Practicals

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 47

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.

Somya Pachauri Ms.Purnima kHURANA


Signature: Signature:

` 2
ACKNOWLEDGEMEN
T
I would like to thank my computer
science teacher (Ms. Purnima Khurana)
who helped me with this practical work.
I’d also like to express my gratitude to
my school principal (Ms. Vandana
Bharadwaj) whole heartedly. I must also
thank my parents and friends for the
immense support and help during this
practical. Without their help,
completing this practical would have
been very difficult.
CONTENT
` 3
Sno. Questions Page no.

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


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 7-9
stack.
3. Write a python program to input details of n students from user and store in 10
a binary file.

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

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

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


equals key or value.

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

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

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

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

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


dictionary.

12. Write a function in Python ADD (Arr), where Arr is a list of numbers. 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.

` 4
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 :

` 5
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()

` 6
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 ")

` 7
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 ")

` 8
OUTPUT:

` 9
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:

10
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()

` 11
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:

if(i.islower()):

` 12
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:

` 13
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)

` 14
OUTPUT:

QUESTION 7:

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

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

f1=open("writetest2.txt","w")

l=f.readlines()

for i in l:

if 'a' in i:

f1.write(i)

` 15
print("file created successfully")

f.close()

f1.close()

OUTPUT:

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

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)

` 16
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()

` 17
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.
CODE:
import pickle
`18
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):

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

sname=input("Enter Name: ")

` 19
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: ')

print('1.Insert Records')

print('2.Dispaly Records')

` 20
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()

` 21
OUTPUT:

` 22
QUESTION 10:

Write a random number generator that generates random numbers between 1


and 6 (simulates a dice).

CODE:
import random

min=1

max=6

roll_again="y"

while roll_again=="y" or roll_again=="Y":

print("Rolling the dice...")

val=random.randint(min,max)

print("You get...:",val)

roll_again=input("Roll the dice again?(y/n)...")

OUTPUT:

` 23
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)

OUTPUT:

` 24
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:

print("Stack is empty")

else:

print(s)

Arr=[25,10,14,30,15,9]

PUSH(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()

max_occuring_word=""

frequency=0

occurances_dict={}

words=content.split()

for word in words:

count=content.count(word)

` 27
occurances_dict.update({word:count})

if(count>frequency):

frequency=count

max_occuring_word=word

print("Most occuring word is:",max_occuring_word)

print("No of times it occured is:",frequency)

print("Other words frequency is :")

print(occurances_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()

`29
OUTPUT:

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")

` 30
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()

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")) ` 31


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",

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:
` 32
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)

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:
` 33
print("Error:Invalid choice try again")
break

OUTPUT:

` 34
`35
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")

` 36
OUTPUT:

` 37
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)

` 38
OUTPUT:

QUESTION 19:

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

CODE:

list = [10, 20, 10, 30, 10, 40, 10, 50]

n = 10

print ("Original list:")

print (list)

i=0

length = len(list)

while(i<length):

` 39
if(list[i]==n):

list.remove(list[i])

length=length -1

continue

i=i+1

print("list after removing elements:")

print(list)

OUTPUT:

` 40
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")

p.dump(l,f)

f.close()

def Countrec(Author):

count=0

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

while True:

try:

l=p.load(f)

` 41
if l[2]==Author:

count=count+1

except EOFError:

print("EOF reached")

break

return count

OUTPUT:

` 42
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

` 43
(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’;
(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 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