Practical File Python Set3
Practical File Python Set3
(BAREILLY)
AFFILIATED TO C.B.S.E BOARD ESTD. 1994
SESSION: - 2026-27
PRACTICAL
PRACTICAL FILE
FILE
COMPUTER SCIENCE
TOPIC-PYTHON & MySQL FILE
SUBMITTED TO:
SUBMITTED BY:
Mr. VIJAY KR. SHARMA ASHUTOSH
AGARWAL
PGT (COMPUTER SCIENCE) 12 TH COMMERCE
BAL VIDYAPEETH PUBLIC SCHOOL
AONLA, BAREILLY
CERTIFICATE
………………….. ………………..
Teacher in-Charge Principal
……………………
External Examiner
ACKNOWLEDGEMENT
Apart from the efforts of me, the success of any project depends largely on
the encouragement and guidelines of many others. I take this opportunity to
express my gratitude to the people who have been instrumental in the successful
completion of this project.
I express deep sense of gratitude to almighty God for giving me strength for
the successful completion of the project.
The guidance and support received from all the members who contributed
and who are contributing to this project, was vital for the success of the project. I
am grateful for their constant support and help.
INDEX
SERIAL TITLE OF PROGRAM PAGE
NO. NO.
1 HCF of two Numbers 4
2 Factorial of a number 5
;
Program: 01 HCF of two Numbers
Write an application program using python to find HCF of Two numbers using function
concept
Program:
Output :
Program:
def factorial(n):
if n == 1:
return n
else:
f=1
for a in range(1,(n+1)):
f*=a
return f
# Main Block
Output:
Enter a number: 6
The factorial of 6 is 720
Program:
def fibo(n):
if n <= 1:
return n
else:
f1=0
f2=1
f=f1+f2
FL=[f1,f2]
while n>0:
[Link](f)
f1=f2
f2=f
f=f1+f2
n=n-1
return FL
#Main Block
nterms = int(input("Enter a number to limit the fibonocci series:"))
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
print(fibo(nterms-2))
Output:
Fibonacci sequence:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
Program:
def sum_arr(arr,size):
if (size == 0):
return 0
else:
sum=0
for a in arr:
sum+=a
return sum
# Main Block
n=int(input("Enter the number of elements for list:"))
a=[ ]
for i in range(0,n):
element=int(input("Enter element"+str(i+1)+":"))
[Link](element)
print("The list is:")
print(a)
print("Sum of items in list:",sum_arr(a,n))
Output:
Enter the number of elements for list:5
Enter element1:10
Enter element2:20
Enter element3:30
Enter element4:40
Enter element5:50
The list is:
[10, 20, 30, 40, 50]
Sum of items in list: 150
Program:
def countWord(str1,word):
s = [Link]()
count=0
for w in s:
if w==word:
count+=1
return count
str1 = input("Enter any sentence :")
word = input("Enter word to search in sentence :")
count = countWord(str1,word)
if count==0:
print("## Sorry! ",word," not present ")
else:
print("## ",word," occurs ",count," times ## ")
Output:
Program:
L = ["God \n", "is \n", "Love\n"] # Creation of list with three lines
count = 1
for line in Lines:
print("Line{}: {}".format(count, [Link]())) # Displaying Each Line of file using
For Loop
count+=1
Output:
Line1: God
Line2: is
Line3: Love
Program:
count = 1
lst=[] # creating a list
for line in Lines:
print("Line{}: {}".format(count, [Link]())) # Displaying Each Line of file using
For Loop
lst. append(line) # Storing each line in to a List
count+=1
print ("Lines in a file is stored in alist : ")
print(lst) #displaying the list
Output:
Line1: Python
Line2: is a
Line3: Programming Language
Lines in a file is stored in alist :
['Python \n', 'is a \n', 'Programming Language \n']
>>>
Program:
Output:
Enter total number of names :4
Enter name1:John
Enter name2:Ram
Enter name3:Raheem
Enter name4:Suraj
File Contents
************
John
Ram
Raheem
Suraj
Program:
Output:
Enter line1:hai
Enter line2:how are you
Enter line3:welcome back
Program:
f = open('[Link]','r')
print ("\nContents in the First file ")
for word in [Link]().split():
print(word, end=' ')
[Link]
s = open('[Link]', 'r')
print ("\nContents in the Second File ")
for word in [Link]().split():
print(word,end=' ')
[Link]()
print ("\nContents in the Second File after copying from the First file: ")
s = open('[Link]', 'r')
for word in [Link]().split():
print(word,end=' ')
[Link]()
Output
First file
***********
Enter total number of Lines :2
Enter Line1:hello
Enter Line2:welcome to SRCS
Second file
***********
Enter total number of Lines :3
Enter Line1:St Raphaels cathedral school
Enter Line2:Senior Secondary school
Enter Line3:CBSE affliated,
Contents in the Second File after copying from the First file:
St Raphaels cathedral school Senior Secondary school CBSE affliated, hello welcome to
SRCS
Program:
Output:
File Entry
***********
Enter total number of Lines :1
Enter Line1:My best school, SRCS
File size in bytes of a plain file: 19
File contents in upper case: MY BEST SCHOOL, SRCS
Program: 12 Store and search Details using Binary file
Write an application program using python,to create binary file to store Rollno and Name,
Search any Rollno and display name if Rollno found otherwise “Rollno not found”
Program:
import pickle
student=[]
f=open('[Link]','wb')
ans='y'
while [Link]()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
[Link]([roll,name])
ans=input("Add More ?(Y)")
[Link](student,f)
[Link]()
f=open('[Link]','rb')
student=[]
while True:
try:
student = [Link](f)
except EOFError:
break
ans='y'
while [Link]()=='y':
found=False
r = int(input("Enter Roll number to search :"))
for s in student:
if s[0]==r:
print("## Name is :",s[1], " ##")
found=True
break
if not found:
print("####Sorry! Roll number not found ####")
ans=input("Search more ?(Y) :")
[Link]()
Output:
Program:
import pickle
student=[]
f=open('[Link]','wb')
ans='y'
while [Link]()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
marks = int(input("Enter Marks :"))
[Link]([roll,name,marks])
ans=input("Add More ?(Y)")
[Link](student,f)
[Link]()
f=open('[Link]','rb+')
student=[]
while True:
try:
student = [Link](f)
except EOFError:
break
ans='y'
while [Link]()=='y':
found=False
r = int(input("Enter Roll number to update :"))
for s in student:
if s[0]==r:
print("## Name is :",s[1], " ##")
print("## Current Marks is :",s[2]," ##")
m = int(input("Enter new marks :"))
s[2]=m
print("## Record Updated ##")
found=True
break
if not found:
print("####Sorry! Roll number not found ####")
ans=input("Update more ?(Y) :")
[Link]()
Output:
Aim:
Write an application program using python, to create CSV file and store
empno,name,salary and search any empno and display name,salary and
if not foundappropriate message.
Program:
import csv
with open('[Link]',mode='a') as csvfile:
mywriter = [Link](csvfile,delimiter=',')
ans='y'
while [Link]()=='y':
eno=int(input("Enter Employee Number "))
name=input("Enter Employee Name ")
salary=int(input("Enter Employee Salary :"))
[Link]([eno,name,salary])
print("## Data Saved... ##")
ans=input("Add More ?")
Output:
Enter Employee Number 1
Enter Employee Name Aswathy
Enter Employee Salary :25000
## Data Saved... ##
Add More ?y
Enter Employee Number 2
Enter Employee Name Riyas
Enter Employee Salary :30000
## Data Saved... ##
Add More ?n
Enter Employee Number to search :2
NAME: Riyas
SALARY : 30000
Search More ? (Y) n
Program:
import random
import time
print("Press CTRL+C to stop the dice ")
play='y'
while play=='y':
try:
while True:
for i in range(10):
print(i)
n = [Link](1,6)
print(n,end='')
[Link](.10)
except KeyboardInterrupt:
print("Your Number is :",n)
ans=input("Play More? (Y) :")
if [Link]()!='y':
play='n'
break
Program:
def isEmpty(S):
if len(S)==0:
return True
else:
return False
def Push(S,item):
[Link](item)
top=len(S)-1
def Pop(S):
if isEmpty(S):
return "Underflow"
else:
val = [Link]()
if len(S)==0:
top=None
else:
top=len(S)-1
return val
def Peek(S):
if isEmpty(S):
return "Underflow"
else:
top=len(S)-1
return S[top]
def Show(S):
if isEmpty(S):
print("Sorry No items in Stack ")
else:
t = len(S)-1
print("(Top)",end=' ')
while(t>=0):
print(S[t],"<==",end=' ')
t-=1
print()
Output:
Aim:
Write an application program totake 10 sample phishing email, and find the most common
word occurring using List
Program:
phishingemail=[
"jackpotwin@[Link]",
"claimtheprize@[Link]",
"youarethewinner@[Link]",
"luckywinner@[Link]",
"spinthewheel@[Link]",
"dealwinner@[Link]",
"luckywinner@[Link]",
"luckyjackpot@[Link]",
"claimtheprize@[Link]",
"youarelucky@[Link]"
]
myd={}
for e in phishingemail:
x=[Link]('@')
for w in x:
if w not in myd:
myd[w]=1
else:
myd[w]+=1
key_max = max(myd,key=[Link])
print("Most Common Occurring word is :",key_max)
Output:
Program:
FB={}
n=int(input(" enter no of details to be need "))
for i in range(n):
print (" FB NO ", i+1)
id=int(input(" enter id "))
na=input(" enter the name ")
pl=input(" enter ur place ")
nk=input(" enter profile name ")
r=[na,pl,nk]
FB[id]=r
k=[Link]()
while True:
c=input(" \n please enter: 'S' for search : 'D' for delete : 'U' for update : ")
if(c in'Ss'):
se=input(" enter the searching name ")
for i in k:
x=FB[i]
if(x[0]==se):
print (" searching record is : NAME : ",x[0]," , PLACE : ",
x[1] ," ,PROFILE NAME : ", x[2])
elif(c in 'dD'):
x=int(input(" enter id "))
if (x in k):
print(" deleted record is ", FB[x])
del FB[x]
else:
print ("invalid id")
elif(c in 'Uu'):
x=int(input (" enter the id "))
if(x in k):
v=FB[x]
na=v[0]
upl=input(" enter place ")
unk=input(" enter profile name")
FB[x]=[na,upl,unk]
print(" updated record is " ,FB[x])
else:
print(" invalid id")
ch=input(" Do you want to continue y/n")
if(ch!='y'):
break
Output:
please enter: 'S' for search : 'D' for delete : 'U' for update : s
enter the searching name sree
searching record is : NAME : sree , PLACE : pkd ,PROFILE NAME : sri
Do you want to continue y/ny
please enter: 'S' for search : 'D' for delete : 'U' for update : u
enter the id 1
enter place thr
enter profile namesreeja
updated record is ['sree', 'thr', 'sreeja']
Do you want to continue y/ny
please enter: 'S' for search : 'D' for delete : 'U' for update : d
enter id 2
invalid id
Do you want to continue y/n
Aim:
Write an application program to, Check whether a number is (i) palindrome (ii)
Armstrong by function with return multiple values
Program:
def calc(n):
s=0
r=0
while n>0:
d=n%10
r=r*10 + d
s=s+d*d*d
n//=10
return s,r
#main
Output:
enter a number 1
ARMSTRONG & PALINDROME
PALINDROME
Program:
Program:
import [Link] as m
def insertion():
try:
con=[Link](host='localhost',user='root',password='123',database='sample')
if(con.is_connected()):
print('Successfully connected')
mycur=[Link]()
empid=int(input("Enter Employee ID :"))
empname= input("Enter employee name :")
query="insert into employee values ({},'{}')".format(empid,empname)
[Link](query)
[Link]()
print ("Record inserted successfully")
[Link]();
[Link]()
except Exception as e:
print(e)
#Main block
insertion()
Output
Successfully connected
Enter Employee ID : 101
Enter employee name :Arjun
Record inserted successfully
Program:
import [Link] as m
def deletion():
try:
con=[Link](host='localhost',user='root',password='123',database='sample')
if(con.is_connected()):
print('successfully connected')
mycur=[Link]()
empid=int(input("Enter Employee ID to be deleted :"))
query="delete from employee where empid={}".format(empid)
[Link](query)
[Link]()
print ("Record deleted successfully")
[Link]();
[Link]()
except Exception as e:
print(e)
#Main Block
deletion()
Output
Successfully connected
Enter Employee ID to be deleted : 101
Program: 22 MY SQL
1. CREATE DATABASE
Create a Database of name EMPLOYEE.
QUERY
2. OPEN COMMAND
Open the Database using the USE command.
QUERY
USE DATA
3. CREATE TABLE
Create table EMP with specified number of rows and columns and apply necessary constraints.
QUERY
CREATE TABLE EMP
(ENO INTEGER PRIMARYKEY, ENAME VARCHAR (20) UNIQUE,
JOB VARCHAR (20) DEFAULT “CLERK”, GENDER CHAR (1) NOT
NULL, HIRE DATE, SAL FLOAT (6,2) CHECK SAL>2000,COMM INTEGER);
4. INSERT COMMAND
Insert tuples to the table EMP.
QUERY
INSERT INTO EMP VALUES(1,’KING’,’MANAGER’,’M’,’1981-11-
17’,5000,NULL);
INSERT INTO EMP VALUES(2,’BLAKE’,’MANAGER’,’M’,’1981-05-
01’,2850,NULL);
INSERT INTO EMP VALUES(3,’JASMIN’,’SALESMAN’,’F’,’1982-12-
09’,2450,300);
INSERT INTO EMP VALUES(4,’JONES’,’SALESMAN’,’M’,’1983-01-
12’,2975,500);
INSERT INTO EMP VALUES(5,’CLARK’,’ANALYST’,’M’,’1983-01-
23’,1250,NULL);
INSERT INTO EMP VALUES(6,’GEETHA’,’CLERK’,’F’,’1981-02-
22’,1600,NULL);
5. SELECT COMMAND
Display all employee details.
QUERY
SELECT * FROM EMP;
OUTPUT
AIM
Display ENO, ENAME and JOB of all Employees.
QUERY
SELECT ENO,ENAME,JOB FROM EMP;
OUTPUT
DISTINCT JOB
MANAGER
SALESMAN
ANALYST
CLERK
OUTPUT
QUERY
SELECT * FROM EMP WHERE ENAME<>’KING’;
OUTPUT
QUERY
SELECT * FROM EMP WHERE JOB=’MANAGER’ OR GENDER=’M’;
OUTPUT
QUERY
SELECT ENO,ENAME,COMM FROM EMP WHERE COMM IS NOT NULL;
OUTPUT
AIM
Display the details of employees whose job is not salesman.
QUERY
SELECT * FROM EMP WHERE JOB NOT=’SALESMAN’;
OUTPUT
AIM
Display the details of employees whose salary is not between 2000 and 5000.
QUERY
SELECT * FROM EMP WHERE SAL NOT BETWEEN 2000 AND 5000;
OUTPUT