Record 20
Record 20
EX.NO:1
Write a Python program to read a text file line by line and display each word
separated by a ‘#’
Aim:
To write Python program to read a text file line by line and display each word
separated by a ‘#’.
Algorithm:
Step 1: Start
Step 2: Open text file in read mode
Step 3: Create string variable
Step 4: Inside of string variable read text file by using of readlines() function.
Step 5: Inside of the looping statements split lines into words using split() then add
Step 7: Stop
Program:
file=open("AI.TXT","r")
lines=file.readlines()
for line in lines:
words=line.split()
for word in words:
print(word+"#",end="")
print("")
file.close()
Output:
1|P ag e
Python Program Executed Output:
Result:
Thus the Python program to read a text file line by line and display each word separated by
a # is executed successfully and the output is verified.
EX.NO:2
Write a Python program to read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file
Aim:
To write Python program to read a text file and display the number of vowels/ consonants/
uppercase/ lowercase characters in the file.
Algorithm:
Step 1: Start
Step 2: Open text file in read mode using open() method
Step 3: Read the content of the file using read() method
Step 4:Write the logic for counting the Vowels,Consonants,Upper case letters,Lower case
letters using islower(),isupper(),ch in [‘a’,’e’,’i’,’o’,’u’],
ch in ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
Step 5: Close the file using close() method
2|P ag e
Step 6: Print the Counting data.
Step 7: Stop
Program:
file=open("AI.TXT","r")
content=file.read()
vowels=0
consonants=0
lower_case_letters=0
upper_case_letters=0
for ch in content:
if(ch.islower()):
lower_case_letters+=1
elif(ch.isupper()):
upper_case_letters+=1
ch=ch.lower()
if (ch in ['a','e','i','o','u']):
vowels+=1
elif(ch in ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']):
consonants+=1
file.close()
print("Vowels are :",vowels)
print("Consonants :",consonants)
print("Lower_case_letters :",lower_case_letters)
print("Upper_case_letters :",upper_case_letters)
Output:
3|P ag e
Python Program Executed Output:
Result:
Thus the Python program to read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file is executed successfully
and the output is verified.
EX.NO:3
Write a Python program to create a binary file with name and roll number and
perform search based on roll number.
Aim:
To write Python Program to create a binary file with name and roll number and perform
search based on roll number.
Algorithm:
Step 1: Start
Step 2: Take the Student data in input from user using for loop
Step 3: Prepare a list of dictionary having student data that is inserted using
for loop in step:2 list-of_students
Step4: Save this list of students in binary file using dump method
file=open(“pathoffile”,”wb”),pickle.dump(list_of_students,file)
Step 5: Read the rollno from user to search
Step 6: open the file in read mode and use load () method to get the
list_of_students object that we have stored in step4
file=open (“pathfile”,”rb”)
list_of_students =pickle.load(file)
Step 7: Search into the list_of_students for given rollno
Step 8: Stop
4|P ag e
Program:
#Create a binary file with name and roll number
import pickle
stud_data={}
list_of_students=[]
no_of_students=int(input("Enter no of Students:"))
for i in range(no_of_students):
stud_data["roll_no"]=int(input("Enter roll no:"))
stud_data["name"]=input("Enter name: ")
list_of_students.append(stud_data)
stud_data={}
file=open("StudDtl.dat","wb")
pickle.dump(list_of_students,file)
print("Data added successfully")
file.close()
#Search for a given roll number and display the name, if not found display appropriate
message.”
import pickle
file=open("StudDtl.dat","rb")
list_of_students=pickle.load(file)
roll_no=int(input("Enter roll no.of student to search:"))
found=False
for stud_data in list_of_students:
if(stud_data["roll_no"]==roll_no):
found=True
print(stud_data["name"],"found in file.")
if (found==False):
print("No student data found. please try again")
file.close()
5|P ag e
Python Program Executed Output:
Result:
Thus the Python program to create a binary file with name and roll number and perform
search based on roll number is executed successfully and the output is verified.
EX NO:4
Write a Python program to create a binary file with roll number, name and marks and
update the marks using their roll numbers.
Aim: To write Python Program to create a binary file with roll number, name and marks
and update the marks using their roll numbers.
Algorithm:
Step 1: Start
Step 2: Take the Student data in input from user using for loop
Step 3: Prepare a list of dictionary having student data that is inserted using
for loop in step:2 list-of_students
6|P ag e
Step4: Save this list of students in binary file using dump method
file=open(“pathoffile”,”wb”) ,pickle.dump(list_of_students,file)
Step 5: Read the rollno from user to search
Step 6: Open the file in read mode and use load () method to get the
list_of_students object that we have stored in step4
file=open (“pathfile”,”rb”)
list_of_students =pickle.load(file)
Step 7: Search into the list_of_studentsfor given rollno and update the marks.
Step 8: Print the updated student_data
Step 9: Stop
Program:
#Create a binary file with roll number, name and marks.
import pickle
student_data={}
no_of_students=int(input("Enter no of Students to insert in file : "))
file=open("StudData","wb")
for i in range(no_of_students):
student_data["RollNo"]=int(input("Enter roll no :"))
student_data["Name"]=input("Enter Student Name :")
student_data["Marks"]=float(input("Enter Students Marks :"))
pickle.dump(student_data,file)
student_data={}
file.close()
print("data inserted Successfully")
7|P ag e
student_data["Marks"]=float(input("Enter marks to update: "))
file.seek(pos)
pickle.dump(student_data,file)
found=True
except EOFError:
if(found==False):
print("Roll no not found")
else:
print("Students marks updated Successfully")
file.close()
Output:
8|P ag e
Result:
Thus the Python program to create a binary file with roll number, name and marks and
update the marks using their roll numbers is executed successfully and the output is
verified.
EX NO:5
Write a Python program to remove all the lines that contain the character ‘a’ in a file
and write it to another file.
Aim: To write a Python program to remove all the lines that contain the character ‘a’ in a file
and write it to another file.
9|P ag e
Algorithm:
Step 1: Start
Step 2: Open text file in read mode using open() method
Step 3: Read the content of the file using readlines() method
Step 4: Close the file using close() method
Step 5: Open 2 different text files in write mode using open() method
Step 6: Remove all the lines from the first file that contains character ‘a’ and removed
lines copied into another file.
Step 7: Close all the files using close () method
Step 8: Stop
Program:
file=open("C:\\Users\\Rec\\format.txt","r")
lines=file.readlines()
file.close()
file=open("C:\\Users\\Rec\\format.txt","w")
file1=open("C:\\Users\\Rec\\second.txt","w")
for line in lines:
if 'a' in line or 'A' in line:
file1.write(line)
else:
file.write(line)
print("Lines containing char 'a' has been removed from format.txt file")
print("Lines containing char 'a' has been saved in second.txt file")
file.close()
file1.close()
Output:
10 | P a g e
Result:
Thus the Python program to remove all the lines that contain the character ‘a’ in a file
and write it to another file is executed successfully and the output is verified.
Exp:6
Write a Python program for random number generation that generates random
numbers between 1 to 6 (simulates a dice).
Aim: To write a Python program for random number generation that generates random
numbers between 1 to 6 (simulates a dice).
Algorithm:
Step 1: Start
Step 2: Import random module
Step 3: Under while loop write a random number generate that will generate number
from 1 to 6 using randint() method.
Step 4: Print the random generate number
Step 5: Stop
11 | P a g e
Program:
import random
while(True):
choice=input("Enter 'r' to roll dice or press any other key to quit: ")
if(choice!="r"):
break
n=random.randint(1,6)
print(n)
Output:
Result:
Thus the Python program for random number generation that generates random numbers
between 1 to 6 (simulates a dice) is executed successfully and the output is verified.
EX NO :7
Write a Python program using function to find the factorial of a natural number.
Aim: To write a Python program using function to find the factorial of a natural number.
Algorithm:
Step 1: Start
12 | P a g e
Step 2: Create user defined function name factorial write following steps
Initialize counter variable i to 1 and fact to 1
Write for loop range(1,n+1)
Calculate fact=fact*i
Return fact
Step 3: Read x value from user.
Step 4: Call the factorial()
Step 5: Print the result.
Step 6: Stop
Program:
def factorial(n):
fact=1
for i in range(1,n+1):
fact=fact*i
return fact
Result:
Thus the Python program using function to find the factorial of a natural number is executed
successfully and the output is verified.
13 | P a g e
EX NO: 8
Write a Python program using function to find the sum of all elements of a list.
Aim: To write a Python program using function to find the sum of all elements of a list.
Algorithm:
Step 1: Start
Step 2: Create user defined function name factorial write following steps
Initialize counter variable i to 1 and fact to 1
Write for loop range(1,n+1)
Calculate fact=fact*i
Return fact
Step 3: Read x value from user.
Step 4: Call the factorial()
Step 5: Print the result.
Step 6: Stop
Program:
def sum_list(items):
sum=0
for i in items:
sum=sum+i
return sum
14 | P a g e
Result:
Thus the Python program using function to find the sum of all elements of a list is executed
successfully and the output is verified.
EX NO:9
Write a Python program using function to compute the nth Fibonacci number.
Aim: To write a python program using function to compute the nth Fibonacci number.
Algorithm:
Step 1: Start
Step 2: Read x value from user.
Step 3: Call the function fibonacci(x) goto step 6 and follow the steps.
Step 4: Print the nth Fibonacci series.
Step 5: Stop
Step 6: Create user defined function name Fibonacci(n) write following steps
Initialize counter variable a=0 and b=1
If n < 0 return invalid input
If n =0 return 0
If n=1 return 1 else
run for loop range(n-2)
compute next number in series: c=a+b
swap a=b
b=c
Return b value
Program:
def fibonacci(n):
a=0
b=1
if n<0:
print ("incorrect input:")
elif n==0:
print(a)
return a
elif n==1:
print(a,b)
15 | P a g e
return b
else:
print(a,b,end=" ")
for i in range(n-2):
c=a+b
print(c,end=" ")
a=b
b=c
return b
print("*Printing Fibonacci Series*")
x=int(input("How many numbers you want to display : "))
print("The Fibonacci Series is: ")
fibonacci(x)
Output:
Result:
Thus the Python program using function to compute the nth Fibonacci number is executed
successfully and the output is verified.
EX NO:10
16 | P a g e
Write a Python program to implement a Stack using a list data-structure.
Aim: To write a Python program to implement a Stack using a list data-structure.
Program:
def push():
a=int(input("Enter the element to be added: "))
stack.append(a)
return a
def pop():
if stack==[]:
print("Stack Underflow!")
else:
print("Deleted element is: ",stack.pop())
def display():
if stack==[]:
print("Stack is Empty!")
else:
for i in range(len(stack)-1,-1,-1):
print(stack[i])
stack=[]
print("STACK OPERATIONS")
choice="y"
while choice=="y":
print("1.PUSH")
print("2.POP")
print("3.DISPLAY")
c=int(input("Enter your choice: "))
if c==1:
push()
elif c==2:
pop()
elif c==3:
display()
else:
17 | P a g e
print("wrong input:")
choice=input("Do you want to continue or not?(y/n): ")
Output:
18 | P a g e
Result:
Thus the Python program to implement a stack using a list data-structure is executed
successfully and the output is verified.
19 | P a g e
EX NO:11
Write a Python program to implement a Queue using a list data-structure.
Program:
def insert():
a=int(input("Enter the element which you want to insert:"))
Queue.append(a)
return a
def delete():
if Queue==[]:
print("Queue is empty....Underflow case....cannot delete the element...")
else:
print("Deleted element is :",Queue.pop())
def display():
if Queue==[]:
print("Queue empty, no elements in QUEUE..")
else:
for i in range(len(Queue)):
print(Queue[i])
Queue=[ ]
print("QUEUE OPERATIONS")
choice="y"
while choice=="y":
print("1.INSERT")
print("2.DELETE")
print("3.DISPLAY ELEMENTS OF QUEUE")
c=int(input("Enter your choice : "))
if c==1:
insert()
elif c==2:
delete()
elif c==3:
display()
else:
20 | P a g e
print("wrong input:")
choice=input("Do you want to continue or not?(y/n) : ")
Output:
Result:
Thus the Python program to implement a Queue using a list data-structure is executed
successfully
21 | P a g e
EX NO:12
Take a sample of ten phishing e-mails (or any text file) and find most commonly
occurringword(s) using Python program.
Aim: To write a Python program to take a sample of ten phishing e-mails (or any text file)
and to find most commonly occurring word(s) in it.
Program:
file=open("email.txt","r")
content=file.read()
max=0
max_occuring_word=""
occurances_dict={}
words=content.split()
count=content.count(word)
occurances_dict.update({word:count})
if(count>max):
max=count
max_occuring_word=word
print(occurances_dict)
Output:
22 | P a g e
Result:
Thus the Python program to take a sample of ten phishing e-mails (or any text file) and finding
most commonly occurring word(s) in it is executed successfully and the output is verified.
23 | P a g e
EX NO:13
Write a Python program to create a CSV file with name and roll number and
perform search for a given roll number and display the name.
Aim: To write a Python program to create a CSV file with name and roll number and
perform search for a given roll number and display the name.
Program:
import csv
def write():
print("Writing Data into CSV file :")
print("-----------------------------")
f=open("student.csv","w",newline="")
swriter=csv.writer(f)
swriter.writerow(["Name","RollNumber"])
rec=[]
while True:
name=input("Enter Name:")
Roll=int(input("Enter Roll Number:"))
data=[name,Roll]
rec.append(data)
ch=input("Do you want to Enter More Records :(Y/N)?")
if ch in"nN":
break
swriter.writerows(rec)
print("Data write in CSV file successfully")
f.close()
def read():
f=open("student.csv","r")
24 | P a g e
print(i)
def search():
while True:
f=open("student.csv","r")
print("searching data from csv file")
print("------------------------------")
s=input("Enter Rollno to be searched:")
found=0
sreader=csv.reader(f)
for i in sreader:
if i[1]==s:
print(i)
found=1
break
if found==0:
print("sorry...no record found")
ch=input("Do you want to Enter More Records: (Y/N)?")
if ch in "nN":
break
f.close()
write()
read()
search()
Output:
25 | P a g e
Result:
26 | P a g e
Thus the Python program to create a CSV file with name and roll number and perform search
for a given roll number and display the name is executed successfully and the output is
verified.
EX NO:14
Result:
Thus the Python program to implement python mathematical functions is executed
successfully and the output is verified.
EX NO:15
Write a Python program to make user defined module and import same in
another module or program.
Aim: To write a Python program to make user defined module and import same in
another module or program.
27 | P a g e
Program:
#Area_square.py
def Square():
area=number*number
print("Area of Square:",area)
#Area_square.py
def Rectangle():
area=l*b
#import package
#import package.py
import usermodule
print(Area_square.square())
print(Area_rect.Rectangle())
Output:
Result:
28 | P a g e
Thus the Python program to make user defined module and import same in another module or
program is executed successfully and the output is verified.
EX NO:16
Write a python program to implement python string functions.
while True:
ch=input("Enter a character:")
if ch.isalpha():
print(ch,"is of alphabets")
elif ch.isdigit():
print(ch,"is a digit")
elif ch.isalnum():
print(ch, "is of aplhabet and numeric")
else:
print(ch,"is of special symbol")
c=input("Do you want to enter more y/n:")
if c in"n":
break
Output:
29 | P a g e
Result:
Thus the Python program implementing python string functions is executed successfully and
the output is verified.
EX NO:17
Write a Program to integrate SQL with Python by importing the MySQL module
and create a record of employee and display the record.
Aim: To write a program to integrate SQL with Python by importing the MySQL
module and create a record of employee and display the record.
Program:
import mysql.connector
con=mysql.connector.connect(host="localhost",user='root',password="",database="empl
oyee")
cur=con.cursor()
#cur.execute("Create table EMPLOYEE(Eno int,Ename varchar(10),Esal float)")
30 | P a g e
query="Insert into employee values({},'{}',{})".format(Eno,Name,salary)
cur.execute(query)
con.commit()
print("row inserted successfully...")
ch=input("Do You Want to enter more records?(y/n)")
if ch=="n":
break
cur.execute("select * from employee")
data=cur.fetchall()
for i in data:
print(i)
Output:
31 | P a g e
Result:
Thus the program to integrate SQL with Python by importing the MySQL module and creating a
record of employee and displaying the record is executed successfully and the output is verified
EX NO:18
Write a Program to integrate SQL with Python by importing the MYSQL module to
search an employee number in table employee and display record, if empno not
found display appropriate message.
Aim: To write a Program to integrate SQL with Python by importing the MYSQL module
to search an employee number in table employee and display record, if empno not found
display appropriate message.
Program:
import mysql.connector as mycon
con = mycon.connect(host='localhost',user='root',password="",
database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE SEARCHING FORM")
32 | P a g e
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO SEARCH :"))
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO", "%20s"%"NAME","%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
ans=input("SEARCH MORE (Y) :")
Output:
33 | P a g e
34 | P a g e
Result:
Thus the program to integrate SQL with Python by importing the MYSQL module to search an
employee number in table employee and display record, if empno not found display appropriate
message is executed successfully and the output is verified.
EX NO:19
Write a Program to integrate SQL with Python by importing the MYSQL module
to update the employee record of entered empno.
Aim: To write a Program to integrate SQL with Python by importing the MYSQL
module to update the employee record of entered empno.
Program:
import mysql.connector as mycon
con = mycon.connect(host='localhost',user='root',password="",
database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE UPDATION FORM")
print("#"*40)
print("\n\n")
35 | P a g e
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:
print("%10s"%"EMPNO","%20s"%"NAME", "%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
choice=input("\n## Are you sure to update? (Y) :")
if choice.lower()=='y':
print("== You can updatethe details ==")
d = input("Enter new Department:")
if d=="":
d=row[2]
try:
n = input("Enter new Name: ")
s = int(input("Enter new Salary: "))
except:
s=row[3]
query="update employee set name='{}',dept='{}',salary={} where
empno={}".format(n,d,s,eno)
cur.execute(query)
con.commit()
print("## RECORD UPDATED ## ")
ans=input("Do you want to update more? (Y) :")
Output:
36 | P a g e
37 | P a g e
Result:
Thus the program to integrate SQL with Python by importing the MYSQL module to update the
employee record of entered empno is executed successfully and output verified.
EX NO:20
Write a Program to integrate SQL with Python by importing the MYSQL module
to delete the record of entered employee number.
Aim: To write a Program to integrate SQL with Python by importing the MYSQL
module to delete the record of entered employee number.
Program:
import mysql.connector as mycon
con = mycon.connect(host='localhost',user='root',password="",
database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE DELETION FORM")
38 | P a g e
print("#"*40)
print("\n\n")
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:
print("%10s"%"EMPNO","%20s"%"NAME", "%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%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:
39 | P a g e
Result:
Thus the program to integrate SQL with Python by importing the MYSQL module to delete the
record of entered employee number is executed successfully and output verified.
40 | P a g e