Comp. Practical - Prisha

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

COMPUTER

SCIENCE
SUBJECT CODE: 083
CLASS: XII

Practical File
(2023-24)

SUBMITTED BY: SUBMITTED TO:


Name: Prisha Ms. Neha Sharma
Stream: Commerce
Roll no.:

1|Page
INDEX
SR.NO. Practical name Page TEACHER
no. SIGN
WAP to find the factorial of a number
1.
WAP to find the Fibonacci series
2.
WAP to find the sum of all the numeric values
3. of a list
WAP to read a text file line by line and display
4. each word separated by hash

WAP to count vowels, Consonants, digits and


5. special characters in a given string

WAP to remove all the lines that contain


6. character ‘a’ in file and write it to another file

WAP to create a binary file with name and


7. roll.no, search for given roll.no and display the
record the roll.no, if not found display
appropriate message
WAP to create a binary file with roll.no, name
8. and marks. Input a roll.no and update marks

WAP to create a random number generator


9. that generates random numbers between 1
and 6 (stimulates a dice)
WAP to create CSV file by entering user-id and
10. password, read and search the password for
the given user-id
Write a program to display ASCII code of a
11. character and vice versa

Program that generates 4 terms of an AP by


12. providing initial and step values to a function
that returns first four terms of the series
WAP to implement append, delete and display
13. elements using a list data structure

Function that take tuples of 6 element and


14. return the sum of element which are divisible
by 3 and 5
2|Page
SR.NO. Practical name PAGE no. TEACHER
SIGN
Program to store details of students into
15. csv file delimitated with tab character

Write a python program to implement


16. stack using a list data structure

Write a python program to implement


17. queue using a list data structure

Create a student table in database and


18. insert the data into the table

ALTER table to add new attributes, modify


19. data type and drop attribute

To UPDATE table to modify data ORDER by


20 to display data in ascending /descending
order.
Write the queries to delete or remove
21. tuple(s) from the table and also write the
query for the use of GROUP BY Clause in
the query
Write the SQL to find the min, max, count,
22. sum and average of the marks in a student
table
Write a program to connect Python with
23. MySQL using database connectivity and
perform the following operations on the
data in database: Create a table and insert
the data into table
Write a program to connect Python with
24. MySQL using database connectivity and
perform the following operations on the
data in database : Fetch the data from the
table created in last practical, Update the
data and Delete the data
WAP to take a sample of phishing
25. emails(or any text file) and find the most
commonly occurring word(s)

3|Page
Practical – 1: WAP to find the factorial of a number.
Program:
Factorial(num):
# single line to find factorial
return 1 if (num==1 or num==0) else num * factorial(num - 1);
# Driver Code
num = int(input("Enter a number: "));
print("Factorial of",num,"is",
factorial(num))
Output:
Case-1
Enter a number: 5
Factorial of 5 is 120
Case-2
Enter a number: 0
Factorial of 0 is 1

4|Page
Practical – 2: WAP to find the fibonacci series.
Program:
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

5|Page
Output:
Case-1
How many terms? 7
Fibonacci sequence:
0
1
1
2
3
5
8
Case-2 Case-3
How many terms? 9 How many terms? 0
Fibonacci sequence: Please enter a positive integer
0
1
1
2
3
5
8
13
21

6|Page
Practical – 3: WAP to find the sum of all the numeric values of a list.
Program:
total = 0
ele = 0
# creating a list
lst = []
n = int(input("Enter number of elements : "))
for i in range(0, n):
ele = int(input())
lst.append(ele) # adding the element
print(lst)
x = sum(lst)
print("The sum of all the elements in the list is: ", x)
Output:
Enter number of elements : 5
67
89
33
21
44
[67, 89, 33, 21, 44]
The sum of all the elements in the list is: 254

7|Page
Practical – 4: WAP to read a text file line by line and display each word
separated by hash.
Program:
file=open("test.txt","r")
for line in file:
print(line)
for word in line.split():
print(word, '#')
print()
file.close
Output:
we work very hard to learn python

we #
work #
very #
hard #
to #
learn #
python #

8|Page
Practical – 5: WAP to count vowels, Consonants, digits and special characters
in a given string.
Program:
file = open("test.txt", "r")
lowercase = 0
uppercase = 0
vowel = 0
consonant = 0
line = file.read()
print (line)
for i in line:
if i >= 'a' and i <= 'z':
lowercase += 1
if i in "aeiou":
vowel += 1
else:
consonant += 1
elif i >= 'A' and i <= 'Z':
uppercase += 1
if i in "AEIOU":
vowel += 1
else:
consonant += 1
print("no.of vowels:", vowel)
9|Page
print("no.of consonat: ", consonant)
print("no. of lowercase letters:", lowercase)
print("no.of uppercase letter:", uppercase)
Output:
we work very hard to learn python

no.of vowels: 8
no.of consonat: 19
no. of lowercase letters: 27
no.of uppercase letter: 0

10 | P a g e
Practical – 6: WAP to remove all the lines that contain character ‘a’ in file and
write it to another file.
Program:
file= openfile= open("test.txt","r")
lines= file.readlines()
file.close()
val=False
file=open("test.txt", "w")
file1=open ("temp.txt", "w")
for line in lines:
if 'a' in line or "A" in line:
val=True
file1.write(line)
else:
file.write(line)
if val==True:
print(" Data uploaded successfully in destination file")
else:
print("data having 'a' letter is not available in source file")
file.close()
file1.close()

11 | P a g e
Output:
Data uploaded successfully in destination file
Test.txt file
Romesh
Bohr

Temp.txt file
Sita
Gita

12 | P a g e
Practical – 7: WAP to create a binary file with name and roll.no, search for
given roll.no and display the record the roll.no, if not found display
appropriate message.
Program:
import pickle
stu={}
stufile=open("stu.dat", "wb")
ans="y"
while ans=="y":
rno=int(input("enter your rollno: "))
name= input("enter your name: ")
stu[ "Rollno"]=rno
stu["Name"]=name
pickle.dump(stu, stufile)
ans=input("Do you want to enter more record(y,n): ")
stufile.close()

import pickle
stu={ }
found=False
fin=open("stu.dat","rb")
rno=int(input("enter the roll no which you want to search: "))
try:
while True:

13 | P a g e
stu=pickle.load(fin)
if stu[ "Rollno"]==rno:
print (stu)
found=True

except EOFError:
if found==False:
print("not found")
else:
print("Search successful")
fin.close()
Output:
enter your rollno: 1
enter your name:abc
Do you want to enter more record(y,n): y
enter your rollno: 2
enter your name: efg
Do you want to enter more record(y,n): n
Enter the rollno which you want to search: 2
{‘Rollno’: 2, ‘Name’: ‘efg’}
Search successful

14 | P a g e
Practical – 8: WAP to create a binary file with roll.no, name and marks. Input a
roll.no and update marks.
Program:
import pickle
stu={ }
stufile=open("stu.dat", "wb")
ans="y"
while ans=="y":
rno=int(input("enter your rollno:"))
name= input ("enter your name:" )
marks= int(input("enter your marks:"))
stu["Rollno"]=rno
stu["Name"]=name
stu["marks"]=marks
pickle. dump (stu, stufile)
ans=input("Do you want to enter more record (y/n):")
stufile.close()

import pickle
stu={ }
found=False
fin=open("stu.dat", "rb+")
rno=int(input("enter the roll no which you want to search:"))
try:
15 | P a g e
while True:
stu=pickle.load(fin)
if stu["Rollno"]==rno:
new_marks-int(input("enter your marks:"))
stu["marks"]=new_marks
pickle. dump (stu, fin)
print(stu)
found=True
except EOFError:
if found==False:
print("roll no not found")
else:
print("marks updated successfully")
fin.close()
Output:
Case-1
enter your rollno:1
enter your name: xyz
enter your marks:25
Do you want to enter more record(y/n):y
enter your rollno:2
enter your name:ijk
enter your marks:23
Do you want to enter more record (y/n):n
16 | P a g e
enter the roll no which you want to search :3
roll no not found
Case-2
enter your rollno:1
enter your name:xyz
enter your marks:25
Do you want to enter more record(y/n):y
enter your rollno:2
enter your name: ijk
enter your marks: 23
Do you want to enter more record(y/n):n
enter the roll no which you want to search: 2
enter your marks:24
{'Rollno': 2, 'Name': 'ijk', 'marks': 24}
marks updated successfully

17 | P a g e
Practical – 9: WAP to create a random number generator that generates
random numbers between 1 and 6 (stimulates a dice).
Program:
import random
min=1
max=6
roll_again="y"
while roll_again=="y":
val=random.randint(1,6)
print("you get ",val)
roll_again=input("do you want to roll again(y/n):")
Output:
you get 4
do you want to roll again(y/n):y
you get 6
do you want to roll again(y/n):y
you get 6
do you want to roll again(y/n):y
you get 5
do you want to roll again(y/n):y
you get 3
do you want to roll again(y/n):n

18 | P a g e
Practical – 10: WAP to create CSV file by entering user-id and password, read
and search the password for the given user-id.
Program:
import csv

login = False
answer = input("Do you have an account? (yes or no) ")

if answer == 'yes' :
with open('upassword.csv', 'r') as csvfile:
csv_reader = csv.reader(csvfile)
username = input("Player One Username: ")
password = input("Player One Password: ")

for row in csv_reader:


if row[0]== username and row[1] == password:
print (row[0], row[1])
print (username, password)
login = True
break
else:
login = False
if login == True:
print("You are now logged in!")
19 | P a g e
else:
print("Incorrect. Game Over.")
exit()
else:
print("Only Valid Usernames can play. Game Over.")
exit()
Output:
Case-1
Do you have an account? (yes or no) yes
Player One Username: ram
Player One Password: 65464
Incorrect. Game Over.
Case-2
Do you have an account? (yes or no) No
Only Valid Usernames can play. Game Over.
Case-3
Do you have an account? (yes or no) yes
Player One Username:abc
Player One Password: 123
abc123
abc123
You are now logged in!

20 | P a g e
Practical 11: Write a program to display ASCII code of a character and vice
versa.
Program:
try:
var=True while
var:
choice=int(input("Press-1 to find the ordinal value of a character \nPress-2 to find a
character of a value\n"))
if choice==1:
ch=input("Enter a character : ") print(ord(ch))
elif choice==2:
val=int(input("Enter an integer value: "))
print(chr(val))
else:
print("You entered wrong choice") print("Do you
want to continue? Y/N") option=input()
if option=='y' or option=='Y': var=True
else:
var = False except:
print("Enter Correct value.")

Output:
Press-1 to find the ordinal value of a character
Press-2 to find a character of a value
1
Enter a character : A 65
Do you want to continue?Y/N

21 | P a g e
Y
Press-1 to find the ordinal value of a character
Press-2 to find a character of a value
2
Enter an integer value: 65
A
Do you want to continue? Y/N
N

22 | P a g e
Practical 12: Program that generates 4 terms of an AP by Providing initial and
step values to a function that returns first four terms of the series.
Program:
def series(n,p):
return n,n+p,n+2*p,n+3*p
for a in range(int(input("how many times you will run this program: "))):
n=int(input("Enter initial value of AP Series: "))
p=int(input("Enter step value of AP Series: ")) print("This
series goes as.....") t1,t2,t3,t4=series(n,p)
print(t1,t2,t3,t4)

Output:
how many times you will run this program: 3 Enter initial
value of AP Series: -1
Enter step value of AP Series: 1 This series
goes as.....
-1 0 1 2
Enter initial value of AP Series: 15 Enter
step value of AP Series: 15 This series goes
as.....
15 30 45 60
Enter initial value of AP Series: -15 Enter step value of AP Series: -5 This series goes as.....
-15 -20 -25 -30

23 | P a g e
Practical 13: WAP to implement append, delete and display elements using a list
data-structure.
Program:
st=[]
print("let's fill st container with some values")
print("we are appending here...")
number=int(input("how many no you want to write: ")) for a
in range(0,number):
num=(input("enter your no:")) st.append(num)
print(st)
print(''' 1.delete
2.display 3.exit
''')
ch=int(input("enter your choice: "))
if ch==1:
if st==[" "]:
print("List is empty")
else:
g=input("which item you want to delete: ")
d=st.remove(g)
print(st)
elif ch==2:
if st==[" "]:
print("List is empty")
else:
print(st)
else:

24 | P a g e
pass

OUTPUT:
Case 1:
let's fill st container with some values
we are appending here...
how many no you want to write: 3
enter your no:12
['12']
enter your no:25 ['12', '25']
enter your no:26 ['12', '25', '26']
1.delete
2.display
3.exit
enter your choice: 1
which item you want to delete: 12
['25', '26']
Case 2:
let's fill st container with some values
we are appending here...
how many no you want to write: 3
enter your no:12
['12']
enter your no:25 ['12', '25']
enter your no:26 ['12', '25', '26']
1.delete 2.display 3.exit
enter your choice: 2 ['12', '25', '26']
25 | P a g e
Practical 14: Function that takes tuple of 6 elements and return the sum of
elements which are divisible by 3 and 5
Program:
def sum(t): s=0
for a in t:
if a%3==0 and a%5==0: s=s+a
return(s) l=[]
for i in range(1,7):
print("Enter your",i,"th element of tuple")
c=int(input("Enter...."))
l.append(c) t=tuple(l)
print("Entered tuple is ",t)
print("sum of the element divisible by 3 and 5 is ",sum(t))

Output:
Enter your 1 th element of tuple Enter….3
Enter your 2 th element of tuple Enter ….15
Enter your 3 th element of tuple Enter ….30
Enter your 4 th element of tuple Enter ….56
Enter your 5 th element of tuple Enter….78
Enter your 6 th number of tuple
Enter….19
Entered tuple is (3, 15, 30, 56, 78, 19)
sum of the element divisible by 3 and 5 is 45

26 | P a g e
Practical 15: Program to store details of students into a csv file delimited with tab
character.
Program:
import csv f=open("stu.csv","w")
swriter=csv.writer(f,delimiter='\t')
swriter.writerow(["Rollno","Name","Marks"]) p=int(input("how
many record you want to enter: ")) for a in range(1,p+1):
print("Record ",a) rollno=int(input("Enter
rollno: ")) name=input("Enter name: ")
marks=int(input("Enter marks: "))
rec=[rollno,name,marks]
swriter.writerow(rec)
f.close()

Output:
how many record you want to enter: 2 Record 1
Enter rollno: 1
Enter name: Ram Enter marks: 45
Record 2
Enter rollno: 4 Enter name: Sita
Enter marks: 43

27 | P a g e
Practical 16: Write a Python program to implement a stack using a list data-
structure
''' Stack works on the principle of “Last-in, first-out”.
To add an item to the top of the list, i.e., to push an item, we use append()
function and to pop out an element we use pop() function.'''
Program:
#program for Stack: try:
NumList = []
Number = int(input("Please enter the Total Number of Stack Values: ")) if Number>0:
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
lengthofstack=len(NumList) print("Original Stack is
:",NumList)
print("your stack has ",lengthofstack," elements.") x=int(input("How many values
do you want to delete?: ")) if(x<=0 or x>lengthofstack):
print("enter correct value.")
else:
for i in range(x): NumList.pop()
print("After Deleting the value, Stack will be: ",NumList) else:
print("Enter postive integer.") except
ValueError:
print("Enter Positive integer only.")

28 | P a g e
OUTPUT:

Please enter the Total Number of Stack Values: 3 Please enter the
Value of 1 Element : 12
Please enter the Value of 2 Element : 13 Please enter the
Value of 3 Element : 14 Original Stack is : [12, 13, 14]
your stack has 3 elements.
How many values do you want to delete?: 2
After Deleting the value, Stack will be: [12]

29 | P a g e
Practical 17: Write a Python program to implement queue using a list data-
structure
''' Queue works on the principle of “First-in, first-out”. In Queue, We use pop(0) to
remove the first item from a list. '''
#program for Queue:
try:
NumList1 = []
Number1 = int(input("Please enter the Total Number of Queue Values: ")) if
Number1>0:
for i1 in range(1, Number1 + 1):
value1 = int(input("Please enter the Value of %d Element : " %i1)) NumList1.append(value1)
lengthofstack1=len(NumList1) print("Original Queue
is :",NumList1)
print("your queue has ",lengthofstack1," elements.") x1=int(input("How
many values do you want to delete?: ")) if(x1<=0 or x1>lengthofstack1):
print("enter correct value.") else:
for i2 in range(x1): NumList1.pop(0)
print("After Deleting the value, queue will be: ",NumList1) else:
print("Enter postive integer.")
except ValueError:
print("Enter Positive integer only.")

30 | P a g e
OUTPUT:

Please enter the Total Number of Stack Values: 3 Please enter


the Value of 1 Element : 12
Please enter the Value of 2 Element : 13 Please enter
the Value of 3 Element : 14 Original Stack is : [12, 13,
14]
your stack has 3 elements.
How many values do you want to delete?: 1 After Deleting
the value, Stack will be: [12, 13]

Please enter the Total Number of Queue Values: 4 Please enter


the Value of 1 Element : 18
Please enter the Value of 2 Element : 19 Please enter
the Value of 3 Element : 17 Please enter the Value of
4 Element : 20 Original Queue is : [18, 19, 17, 20]
your queue has 4 elements.
How many values do you want to delete?: 3 After Deleting
the value, queue will be: [20]

31 | P a g e
Practical 18: Create a student table in the database and insert the data
into the table
Program:
1. We will create a database having name stu_record using the following query:

create database stu_record;


Output:
1 queries executed, 1 success, 0 errors, 0 warnings Query: create
database stu_record
1 row(s) affected
Execution Time : 0.004 sec Transfer Time :
0.002 sec Total Time : 0.006 sec
2. Select the database in which we want to create the table

USE stu_record;
Output:
1 queries executed, 1 success, 0 errors, 0 warnings Query: use stu_record
0 row(s) affected
Execution Time : 0.001 sec Transfer Time :
0.002 sec Total Time : 0.004 sec
3. To create the table student, execute the following query:

CREATE TABLE student


(
student_id BIGINT(20) NOT NULL AUTO_INCREMENT,
student_name VARCHAR(50) NOT NULL, father_name
VARCHAR(80) NULL, PRIMARY KEY(student_id)
);

32 | P a g e
1 queries executed, 1 success, 0 errors, 0 warnings
Query: create table student ( student_id bigint(20) Not null auto_increment, student_name
varchar(50) Not Null, father_name varchar(80)...
0 row(s) affected Execution Time : 0.607
sec Transfer Time : 0.001 sec Total Time
: 0.609 sec
4. To insert the data into the student table

INSERT INTO student (student_name, father_name) VALUES('Priya', 'Mr. XYZ'); INSERT INTO
student (student_name, father_name) VALUES('Nikhil', ''); INSERT INTO student
(student_name) VALUES('Shruti');

33 | P a g e
Practical 19: ALTER table to add new attributes, modify data type and
drop attribute
Assumptions:
1. Database having name stu_record is already created.
2. Student table has been already created having three
attributes: student_id BIGINT(20) NOT NULL
AUTO_INCREMENT, student_name VARCHAR(50) NOT NULL,
father_name VARCHAR(80) NULL, PRIMARY
KEY(student_id)

Program:
ALTER table student to add new attribute adm_number:
ALTER TABLE student
ADD COLUMN adm_number VARCHAR(10) NULL;

Output:
1 queries executed, 1 success, 0 errors, 0 warnings
Query: ALTER TABLE student ADD COLUMN adm_number VARCHAR(10) NULL
0 row(s) affected
Execution Time : 1.255 sec
Transfer Time : 0.001 sec
Total Time : 1.256 sec
1. Modify Data type of attribute adm_number in table student:

ALTER TABLE student


CHANGE adm_number adm_num BIGINT(20) NULL;
Message:
1 queries executed, 1 success, 0 errors, 0 warnings

34 | P a g e
Query: ALTER TABLE student CHANGE adm_number adm_num BIGINT(20) NULL 3 row(s)
affected
Execution Time : 2.445 sec
Transfer Time : 0 sec
Total Time : 2.446 sec

2.To drop attribute adm_num from the table student: ALTER


TABLE student DROP COLUMN adm_num;
1 queries executed, 1 success, 0 errors, 0 warnings
Query: ALTER TABLE student DROP COLUMN adm_num
0 row(s) affected
Execution Time : 1.608 sec Transfer
Time : 0 sec
Total Time : 1.609 sec

35 | P a g e
Practical 20: To UPDATE table to modify data ORDER By to display data in
ascending/ descending order
Assumptions:
1.Database having name stu_record is already created.
2.Student table has been already created having three attributes: student_id
BIGINT(20) NOT NULL AUTO_INCREMENT, student_name VARCHAR(50) NOT
NULL,
father_name VARCHAR(80) NULL, adm_no varchar(10)
NULL, PRIMARY KEY(student_id)
3.Student table has some of the data in it.

Program:
1. To UPDATE table to modify data:

UPDATE student SET father_name='ABCD' WHERE student_id='2';


Output:

1 queries executed, 1 success, 0 errors, 0 warnings


Query: update student Set father_name='ABCD' where student_id='2'
36 | P a g e
1 row(s) affected
Execution Time : 0.118 sec
Transfer Time : 0 sec
Total Time : 0.119 sec
2. To display data in ascending descending order:
a. to show data in ascending order ORDER BY admission number
SELECT student_name, father_name, adm_no FROM student ORDER BY adm_no ASC;
OR
SELECT student_name, father_name, adm_no FROM student ORDER BY adm_no;

OUTPUT:

b. To show data in descending order ORDER BY admission number


SELECT student_name, father_name, adm_no FROM student ORDER BY adm_no desc;
OUTPUT:

37 | P a g e
Practical 21: Write the queries to delete or to remove tuple(s) from the table
and also write the query for the use of GROUP BY Clause in the query.
Assumptions:
1.Database having name stu_record is already created.
2.Student table has been already created having three attributes: student_id BIGINT(20)
NOT NULL AUTO_INCREMENT, student_name VARCHAR(50) NOT NULL,
father_name VARCHAR(80) NULL, adm_no
varchar(10) NULL,
class_name varchar(10) NOT NULL, PRIMARY
KEY(student_id)
3.Student table has some of the data in it.

Program:
1. To Delete the tuple from the table student:

DELETE FROM student WHERE student_id='3';

Output:

1 queries executed, 1 success, 0 errors, 0 warnings Query: Delete from


student where student_id='3'
0 row(s) affected
Execution Time : 0.002 sec Transfer Time :
0.008 sec Total Time : 0.011 sec
2. Use of GROUP BY Clause in Select Query:
SELECT class_name, COUNT(*) AS countings FROM student GROUP BY class_name;
38 | P a g e
OUTPUT:

39 | P a g e
Practical 22: Write the queries in SQL to find the min, max, sum, count and
average of the marks in a student table
Assumptions:
1.Database having name stu_record is already created.
2.Student table has been already created having three attributes: student_id BIGINT(20) NOT
NULL AUTO_INCREMENT, student_name VARCHAR(50) NOT NULL,
father_name VARCHAR(80) NULL, adm_no varchar(10) NULL, class_name varchar(10) NOT
NULL, PRIMARY KEY(student_id)
3.Student table has some of the data in it.

Program:
1. Query to get count:

SELECT COUNT(*) AS xii_count FROM student WHERE class_name='XII';


OUTPUT:

2. Query to find the min, max, sum and average of the marks

SELECT MIN(adm_no), MAX(adm_no), SUM(adm_no), AVG(adm_no) FROM student;

40 | P a g e
Practical 23: Write a program to connect Python with MySQL using database
connectivity and perform the following operations on data in the database:
Create a table and Insert the data into the table.
Program A: CREATE A TABLE
import mysql.connector
demodb =mysql.connector.connect(host="localhost", user="root", passwd="",
database="student")
democursor=demodb.cursor( )
query="CREATE TABLE STUDENT (admn_no int primary key, sname varchar(30), gender
char(1), DOB date, stream varchar(15), marks float(4,2))"
democursor.execute(query) demodb.close()
Program B: INSERT THE DATA
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root", passwd="",
database="test")
democursor=demodb.cursor( )
query= "insert into student(admn_no,sname,gender,DOB,stream,marks) values (%s, %s, %s,
%s,%s, %s)"
tuple1=(1245, 'Arush', 'M', '2003-10-04', 'science', 67.34)
democursor.execute(query, tuple1)
demodb.commit( )
demodb.close()

41 | P a g e
Practical 24: Write a program to connect Python with MySQL using database
connectivity and perform the following operations on data in the database: Fetch
the data from the table created in last practical, Update the data and Delete the
data.
Program A: FETCH THE DATA
import mysql.connector demodb =
mysql.connector.connect(host="localhost", user="root", passwd="", database="test")
democursor=demodb.cursor( )
democursor.execute("select * from student")
data=democursor.fetchall()
for i in data: print(i)
demodb.close()

Program B: UPDATE THE DATA


import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root", passwd="",
database="test")
democursor=demodb.cursor( )
query="update student set marks=%s where admn_no=%s"
tuple1=(55.68,1245)
democursor.execute(query,tuple1)
demodb.commit( )
demodb.close()

Program C: DELETE THE DATA


import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root", passwd="",
database="test")

42 | P a g e
democursor=demodb.cursor( )
query="delete from student where admn_no=%s"
tuple1=(1245,)
democursor.execute(query,tuple1)
demodb.commit( )

43 | P a g e
PRACTICAL 25: WAP to take a sample of phishing emails (or any text file) and
find the most commonly occurring word(s).
1. Robocalls are on rise.be wary of any pre recorded messages you might receive.
2. Password will expire in 2 days click here to to validate Email account.
3. Your personal security for your wells account has expired as a result it is no longer
valid. this email has been sent to safeguard your wells account from any unauthorized
activity .for your online account safety click the link below to reactivate your key
<http://cabin.com/wells key account5/page2.html>
4. You won a lottery of 5 lakh rupees . click here to get a prize. share your username
and password. click here: http://lottery.com/prize.html
5. I have noticed your banking site is down .please share your username and password
urgently to block it in response of this email
6. You are a student of class X, pay your fees online and you will get coupen of five lakh
rupees by sharing your username and password.
Program
from collections import Counter
ph=open("phishing_email.txt","r")
r=ph.read()
data_set=r.lower()
def most_common_word(n): split_it =
data_set.split()
count = Counter(split_it)
most_occur = count.most_common(n)
print(most_occur)
n=int(input("Enter the no. of words, you wanna display."))
most_common_word(n)

44 | P a g e
OUTPUT: CASE 1:
Enter the no. of words, you wanna display.10
[('your', 9), ('to', 6), ('of', 5), ('click', 4), ('and', 4), ('username', 3), ('are', 2), ('any', 2), ('you',
2),('will', 2)]

CASE 2:
Enter the no. of words, you wanna display.25
[('your', 9), ('to', 6), ('of', 5), ('click', 4), ('and', 4), ('username', 3), ('are', 2), ('any', 2), ('you',
2),('will', 2), ('in', 2), ('here', 2), ('for', 2), ('wells', 2), ('has', 2), ('a', 2), ('it', 2), ('is', 2), ('email',
2),('account', 2), ('.', 2), ('online', 2), ('key', 2), ('lakh', 2), ('get', 2)]

45 | P a g e

You might also like