Practical File
Practical File
Program 1
Q. Read a text file line by line and display each word separated by a #.
1
Ans.
f=open("story.txt","w")
s=input("enter a story:")
f.write(s)
f.close( )
f=open("story.txt","r")
doc=f.readlines( )
for i in doc:
words=i.split( )
for a in words:
print(a,end="#")
f.close( )
Output:
enter a story:I study in APS CT
I#study#in#APS#CT#
Program 2
2
Ans.
f=open("PARA.txt","w")
s=input("Enter a para:")
f.write(s)
f.close( )
f=open("PARA.txt","r")
f1=f.read()
v,c,u,l=0,0,0,0
for ch in f1:
if ch in 'aeiouAEIOU':
v+=1
if ch not in 'aeiouAEIOU':
c+=1
if ch.isupper( ):
u+=1
if ch.islower( ):
l+=1
print("No. of vowels",v)
print("No. of consonants",c)
print("No. of uppercase characters",u)
print("No. of lowercase characters",l)
f.close( )
Output:
Enter a para:IstudyinAPSCT
No. of vowels 4
No. of consonants 9
No. of uppercase characters 6
No. of lowercase characters 7
Program 3
Q. 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.
3
Ans.
import pickle
import sys
dict={}
def write():
f=open("student.dat","ab") # a-append, b-binary
n=int(input("Enter no. of students"))
for i in range(n):
print("Enter student",i+1,"details")
dict["roll"]=int(input("Enter the rollno"))
dict["name"]=input("enter the name")
pickle.dump(dict,f) # dump- to write in student file
f.close()
def search():
f=open("student.dat","rb") # r-read, b-binary
r=int(input("enter the rollno to search"))
found=0
try:
while True:
data=pickle.load(f) # load-reads from file
if data["roll"]==r:
print(data)
found=1
break
except EOFError:
pass
if found==0:
print("record not found")
f.close()
while True:
print("MENU\n 1-Write in file\n 2-Search\n 3-Exit")
ch=int(input("Enter your choice"))
if ch==1:
write()
if ch==2:
search()
if ch==3:
4
sys.exit()
Output:
MENU
1-Write in file
2-Search
3-Exit
Enter your choice1
Enter no. of students2
Enter student 1 details
Enter the rollno1
enter the nameAjay
Enter student 2 details
Enter the rollno2
enter the nameAnil
MENU
1-Write in file
2-Search
3-Exit
Enter your choice2
enter the rollno to search1
{'roll': 1, 'name': 'Ajay'}
MENU
1-Write in file
2-Search
3-Exit
Enter your choice3
Program 4
Q. Create a binary file with roll number, name and marks. Input a roll number and
update the marks.
Ans.
import pickle
student=[]
5
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll=int(input("Enter Roll Number:"))
name=input("Enter Name:")
marks=int(input("Enter Marks:"))
student.append([roll,name,marks])
ans=input("Add More?(Y)")
pickle.dump(student,f)
f.close()
f=open('student.dat','rb+')
student=[]
while True:
try:
student=pickle.load(f)
except EOFError:
break
ans='y'
while ans.lower()=='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:"))
print("Record Updated")
found=True
break
if not found:
print("Roll number not found")
ans=input("update more?(Y):")
f.close()
Output:
Program 5
Q. Remove all the lines that contain the character `a' in a file and write it to another
file.
Ans.
7
f=open("first.txt","w")
f.write("a quick brown fox\n")
f.write("one two three four\n")
f.write("five six seven\n")
f.write("India is my country\n")
f.write("eight nine ten\n")
f.write("bye!")
f.close( )
f=open("first.txt","r")
lines=f.readlines()
f.close()
f1=open("second.txt","w")
for line in lines:
if 'a' not in line:
f1.write(line)
print("##File copied successfully##")
f1.close()
f=open("first.txt","r")
print("The contents of first file is:")
print(f.read())
f1=open("second.txt","r")
print("The contents of second file is:")
print(f1.read())
Output:
##File copied successfully##
The contents of first file is:
a quick brown fox
one two three four
five six seven
India is my country
eight nine ten
bye!
The contents of second file is:
one two three four
five six seven
eight nine ten
bye!
8
Program 6
Q. Create a CSV file with empno,name and salary. Search for a given empno and
display the name,salary and if not found display appropriate message.
Ans.
import csv
9
with open('myfile.csv','w') as csvfile:
mywriter=csv.writer(csvfile,delimiter=',')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter Employee Number:"))
name=input("Enter Employee Name:")
salary=int(input("Enter Employee Salary:"))
mywriter.writerow([eno,name,salary])
ans=input("Add More?(Y)")
ans='y'
with open('myfile.csv','r') as csvfile:
myreader=csv.reader(csvfile,delimiter=',')
while ans=='y':
found=False
e=int(input("Enter Employee Number to search:"))
for row in myreader:
if len(row)!=0:
if int(row[0])==e:
print("NAME:",row[1])
print("SALARY:",row[2])
found=True
break
if not found:
print("EMPNO NOT FOUND")
ans=input("Search More?(Y)")
Output:
Program 7
Q. Write a random number generator that generates random numbers between 1
and 6 (simulates a dice).
Ans.
import random
11
import time
print("Press CTRL+C to stop the dice")
play='y'
while play=='y':
try:
while True:
for i in range(10):
print()
n=random.randint(1,6)
print(n,end='')
time.sleep(.00001)
except KeyboardInterrupt:
print("Your Number is:",n)
ans=input("Play More?(Y):")
if ans.lower()!='y':
play='n'
break
Output:
4Your Number is : 4
Play More? (Y) :y
Your Number is : 3
Play More? (Y) :y
Your Number is : 2
Play More? (Y) :n
Program 8
Q. Write a Python program to implement a stack using a list data-structure.
Ans.
# Implementation of List as stack
s=[]
12
c="y"
while c=="y":
print("1. PUSH")
print("2. POP")
print("3. Display")
choice=int(input("Enter your choice: "))
if choice==1:
a=input("Enter any number :")
s.append(a)
elif choice==2:
if s==[]:
print("Stack Empty")
else:
print("Deleted element is : ",s.pop())
elif choice==3:
l=len(s)
for i in range(l-1,-1,-1): # to display elements from last element to first
print(s[i])
else:
print("Wrong Input")
c=input("Do you want to continue or not? ")
Output:
1. PUSH
2. POP
3. Display
Enter your choice:1
Enter any number :5
Do you want to continue or not? y
1. PUSH
2. POP
3. Display
Enter your choice:1
Enter any number :t
Do you want to continue or not? y
1. PUSH
2. POP
3. Display
Enter your choice:1
13
Enter any number :66
Do you want to continue or not? y
1. PUSH
2. POP
3. Display
Enter your choice:1
Enter any number :88
Do you want to continue or not? y
1. PUSH
2. POP
3. Display
Enter your choice:3
88
66
t
5
Do you want to continue or not? y
1. PUSH
2. POP
3. Display
Enter your choice:2
Deleted element is : 88
Do you want to continue or not? y
1. PUSH
2. POP
3. Display
Enter your choice:2
Deleted element is : 66
Do you want to continue or not? y
1. PUSH
2. POP
3. Display
Enter your choice:3
t
5
Do you want to continue or not? n
14
Program 9
Q. Program to take a sample of ten phishing e-mails (or any text file) and find
most commonly occurring word(s)
Ans.
#Program to take 10 sample phishing and count the most commonly occurring
#word
15
phishingemail=["jackpotwin@lottery.com",
"claimtheprize@mymoney.com",
"youarethewinner@lottery.com",
"luckywinner@mymoney.com",
"spinthewheel@flipkart.com",
"dealwinner@snapdeal.com" ,
"luckywinner@snapdeal.com",
"luckyjackpot@americanlotter",
"claimtheprize@lootolottery.co",
"youarelucky@mymoney.com"
]
myd={}
for e in phishingemail:
x=e.split('@')
for w in x:
if w not in myd:
myd[w]=1
else:
myd[w]+=1
key_max = max(myd,key=myd.get)
print("Most Common Occuring word is :",key_max)
Output:
Most Common Occuring word is : mymoney.com
Program 10
Ans.
# Program to calculate factorial of entered number
num = int(input("Enter any number :ʺ))
16
fact =1
n = num # storing num in n for printing
while num>0:
fact = fact * num
num- =1
print("Factorial of ", n , " is :",fact)
Output:
Program 11
Q. Input any number from user and check if it is Prime no. or not.
Ans.
# To take input from the user
num = int(input("Enter a number: "))
17
# prime numbers are greater than 1
if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
break
else:
print(num,"is a prime number")
Output:
Enter a number: 7
7 is a prime number
>>>
Enter a number: 21
21 is not a prime number
>>>
Enter a number: 21
21 is not a prime number
>>>
Enter a number: 13
13 is a prime number
>>>
Enter a number: 9
9 is not a prime number
>>>
Enter a number: 21
21 is not a prime number
18
Program 12
Ans.
#Program to find the occurence of any word in a string
def countWord(str1,word):
s = str1.split()
19
count=0
for w in s:
if w==word:
count+=1
return count
Output:
Enter any sentence :my computer your computer our computer everyones computer
Enter word to search in sentence :computer
## computer occurs 4 times ##
Program 13
Q. Using function find sum of all the elements of a list.
Ans.
def Sumlist(L1):
s=0
for i in L1:
s+=i
20
return s
Output:
Program 14
Q. Write a program using user defined function that accepts base and exponent as
arguments and returns the value Base exponent where Base and exponent are
integers.
Ans.
#Function to calculate and display base raised to the power exponent
21
#The requirements are listed below:
#1. Base and exponent are to be accepted as arguments.
#2. Calculate Baseexponent
#3. Return the result (use return statement )
#4. Display the returned value.
Output:
Program 15
Q. Write a program using user defined function to compute the nth Fibonacci
number.
Ans.
def fibo(n1):
a=0
22
b=1
print(a)
print(b)
for i in range(1,n1-1):
c=a+b
print(c)
a,b=b,c
Output:
Program 16
Q. Write a program using user defined function that accepts length and breadth of a
rectangle and returns the area and perimeter of the rectangle.
Ans.
#Function to calculate area and perimeter of a rectangle
#The requirements are listed below:
23
#1. The function should accept 2 parameters.
#2. Calculate area and perimeter.
#3. Return area and perimeter.
def calcAreaPeri(Length,Breadth):
area = length * breadth
perimeter = 2 * (length + breadth)
#a tuple is returned consisting of 2 values area and perimeter
return (area,perimeter)
l = float(input("Enter length of the rectangle: "))
b = float(input("Enter breadth of the rectangle: "))
#value of tuples assigned in order they are returned
area,perimeter = calcAreaPeri(l,b)
print("Area is:",area,"\nPerimeter is:",perimeter)
Output:
Program 17
Q. Program to connect with database and store record of employee and display
records.
Ans.
import mysql.connector as mycon
con = mycon.connect(host='localhost',user='root',password='mysql')
cur = con.cursor( )
cur.execute("create database company")
24
cur.execute("use company")
cur.execute("create table employee(empno int, name varchar(20), dept
varchar(20),salary int)")
con.commit( )
choice=None
while choice!=0:
print("1. ADD RECORD ")
print("2. DISPLAY RECORD ")
print("0. EXIT")
choice = int(input("Enter Choice :"))
if choice == 1:
e = int(input("Enter Employee Number :"))
n = input("Enter Name :")
d = input("Enter Department :")
s = int(input("Enter Salary :"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
cur.execute(query)
con.commit()
elif choice == 2:
query="select * from employee"
cur.execute(query)
result = cur.fetchall()
for row in result:
print(row[0],row[1],row[2],row[3])
elif choice==0:
con.close()
print("## Bye!! ##")
else:
print("## INVALID CHOICE ##")
Output:
1.ADD RECORD
2.DISPLAY RECORD
0.EXIT
Enter Choice :1
Enter Employee Number :1
Enter Name :AMIT
Enter Department :SALES
25
Enter Salary :9000
1.ADD RECORD
2.DISPLAY RECORD
0.EXIT
Enter Choice :1
Enter Employee Number :2
Enter Name :NITIN
Enter Department :IT
Enter Salary :80000
1.ADD RECORD
2.DISPLAY RECORD
0.EXIT
Enter Choice :2
1 AMIT SALES 9000
2 NITIN IT 80000
1.ADD RECORD
2.DISPLAY RECORD
0.EXIT
Enter Choice :0
## Bye!! ##
Program 18
Q. Program to connect with database and search employee number in table
employee
and display record, if empno not found display appropriate message.
Ans.
import mysql.connector as mycon
con=mycon.connect(host='localhost',user='root',password='mysql',database='compa
ny')
26
cur = con.cursor( )
ans='y'
while ans.lower( )=='y':
eno = int(input("ENTER EMPNO TO SEARCH :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
for row in result:
print(row[0],row[1],row[2],row[3])
ans=input("SEARCH MORE (Y/N) :")
Output:
Program 19
Q. Program to connect with database and update the employee record of entered
empno.
Ans.
import mysql.connector as mycon
con =
mycon.connect(host='localhost',user='root',password='mysql',database="company")
27
cur = con.cursor( )
ans='y'
while ans.lower()=='y':
eno =int(input("ENTER EMPNO TO UPDATE :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
for row in result:
print(row[0],row[1],row[2],row[3])
choice=input("\n## ARE YOUR SURE TO UPDATE ? (Y) :")
if choice.lower()=='y':
print("== YOU CAN UPDATE ONLY DEPT AND SALARY ==")
print("== FOR EMPNO AND NAME CONTACT ADMIN ==")
d = input("ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT
WANT TO CHANGE )")
s = int(input("ENTER NEW SALARY,(LEAVE BLANK IF NOT WANT
TO CHANGE ) "))
query="update employee set dept='{}',salary={} where
empno={}".format(d,s,eno)
cur.execute(query)
con.commit()
print("## RECORD UPDATED ## ")
ans=input("UPDATE MORE (Y) :")
Output:
Program 20
Q. Program to connect with database and delete the record of entered employee
number.
Ans.
import mysql.connector as mycon
con =
mycon.connect(host='localhost',user='root',password='mysql',database='company')
29
cur = con.cursor( )
ans='y'
while ans.lower( )=='y':
eno = int(input("ENTER EMPNO TO DELETE :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall( )
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
for row in result:
print(row[0],row[1],row[2],row[3])
choice=input("\n## ARE YOUR SURE TO DELETE ? (Y) :")
if choice.lower( )=='y':
query="delete from employee where empno={}".format(eno)
cur.execute(query)
con.commit()
print("=== RECORD DELETED SUCCESSFULLY! ===")
ans=input("DELETE MORE ? (Y) :")
Output:
30
Empn EmpName Job Mgr Hiredate Sal comm Deptno
o
7839 KING PRESIDEN 7839 17-Nov-81 5000 10
T
Fig. 1
1. To show the content of the EMP table
Ans. SELECT * FROM EMP;
Output:- Fig. 1
2. To display distinct jobs from the EMP table
31
Ans. SELECT DISTINCT Job FROM EMP;
Output:- PRESIDENT
MANAGER
SALESMAN
CLERK
ANALYST
34
10. To calculate the total salary for employees having deptno=10
Ans. SELECT SUM(Sal) FROM EMP WHERE Deptno=10;
Output:- 7450
35
13. To insert a new row in the EMP table with the following data:
7950, “RAM”, “ANALYST”,7900,{28/03/84},6000
Ans. INSERT INTO EMP VALUES(7950, “RAM”,
“ANALYST”,7900,{28/03/84},6000);
Output:- This row will be inserted at the end of table.
36