Somya - Xii (A) - 60 - CS Practicals
Somya - Xii (A) - 60 - CS Practicals
Somya - Xii (A) - 60 - CS Practicals
VIDYALAYA
Computer Science
PRACTICAL FILE
` 1
CERTIFICATE:
` 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.
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.
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).
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:
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=[]
for n in range(num):
lst.append(numbers)
print("original list:",lst)
leexchange()
` 6
OUTPUT:
QUESTION 2:
CODE:
s=[]
c="y"
print("1.PUSH")
print("2.POP")
print("3.DISPLAY")
if choice==1:
` 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()
elif choice==3:
i=len(s)
while i>0:
print(s[i-1])
i=i-1
else:
print("wrong input")
` 8
OUTPUT:
` 9
QUESTION 3:
s={}
file2=open("student.dat",'wb')
N=input("Enter name")
M=float(input("Enter marks"))
s['Rollno']=R
s['Name']=N
s['Marks']=M
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=[]
for i in range(0,n):
L.append(ele)
print("original list",L)
reverse()
` 11
OUTPUT:
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:
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
d=list(d.items())
print(d)
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:
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):
srecord={"SROLL":sroll,"SNAME":sname}
pickle.dump(srecord,Myfile)
def Readrecord():
print()
while True:
try:
rec=pickle.load(Myfile)
except EOFError:
break
def Input():
` 19
Writerecord(sroll,sname)
def SearchRecord(roll):
while True:
try:
rec=pickle.load(Myfile)
if rec['SROLL']==roll:
print("Roll NO:",rec['SROLL'])
print("Name:",rec['SNAME'])
except EOFError:
print("Try Again..............")
break
def main():
while True:
print('1.Insert Records')
print('2.Dispaly Records')
` 20
print('3.Search Records (By Roll No)')
if ch==1:
Input()
elif ch==2:
Readrecord()
elif ch==3:
SearchRecord(r)
else:
break
main()
` 21
OUTPUT:
` 22
QUESTION 10:
CODE:
import random
min=1
max=6
roll_again="y"
val=random.randint(min,max)
print("You get...:",val)
OUTPUT:
` 23
QUESTION 11:
while True :
choice = input("Do you want to Enter another record Press 'y' if yes : ")
if choice != "y" :
break
print(emp_dict)
OUTPUT:
` 24
QUESTION 12:
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:
n=len(L)
last=L[n-1]
for i in range(n-2,-1,-1):
L[i+1]=L[i]
L[0]=last
L)
L=[]
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()
count=content.count(word)
` 27
occurances_dict.update({word:count})
if(count>frequency):
frequency=count
max_occuring_word=word
print(occurances_dict)
OUTPUT:
` 28
QUESTION 15:
CODE:
import mysql.connector
mydb=mysql.connector.connect(host="localhost", user="root",
passwd="mysql", database="real_estate")
mycursor=mydb.cursor()
mycursor.close()
mydb.close()
`29
OUTPUT:
QUESTION 16:
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")
while True:
if choice==1:
mydb=mysql.connector.connect(host="localhost",
user="root",
passwd="mysql",
database="real_estate")
mycursor=mydb.cursor()
mydb.close()
break
elif choice==2:
mydb=mysql.connector.connect(host="localhost",
user="root",passwd="mysql", database="real_estate")
mycursor=mydb.cursor()
adrs=str(input("Enter address"))
VALUES({},'{}','{}')". format(id,name,adrs)
mycursor.execute(sql)
mydb.commit()
mydb.close()
break
elif choice==3:
mydb=mysql.connector.connect(host="localhost",
user="root",
passwd="mysql",
database="real_estate")
mycursor=mydb.cursor()
mycursor.execute(query)
mydb.commit()
break
elif choice==4:
` 32
mydb=mysql.connector.connect(host="localhost",
user="root", passwd="mysql", database="real_estate")
mycursor=mydb.cursor()
mycursor.execute(query)
mydb.commit()
print("Deletion sccessfully")
break
elif choice==5:
mydb=mysql.connector.connect(host="localhost",
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 ():
if l1[i]%3==0:
l1[i]=l1[i]//3
elif l1[i]%5==0:
l1[i]=l1[i]*2
l1 = []
for n in range(num):
l1.append(numbers)
manipulate()
print("END OF FUNCTION")
` 36
OUTPUT:
` 37
QUESTION 18:
def square_cube(L,n):
h=int(n/2)
for i in range(0,h):
L[i]=L[i]*L[i]
L[j]=L[j]**3
L=[]
for i in range(0,n):
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:
n = 10
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)
OUTPUT:
` 40
QUESTION 20:
import pickle as p
def Createfile():
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
TABLE: SGRADE
` 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 :
COUNT(SGRADE) SGRADE
2 S03
2 S02
1 S01
MIN(DOB) MAX(DOJ)
1980-01-13 2010-02-12
SGRADE SALARY+HRA
S02 44000
` 45