classXII-CS-Record Programs
classXII-CS-Record Programs
Program to count number of times the character the given appears in the text file.
AIM: To write a Program to count number of times the character the given appears in the text file.
PROGRAM:
def write_txt():
f=open("text1.txt",'w')
ans='Y'
while ans.upper()=='Y':
line=input("Enter a line: ")
f.write(line+"\n")
ans=input("Do you want to add one more line......(Y/N): ")
f.close()
def read_txt():
count_A=0
f=open("text1.txt","r")
str=f.read()
print(str)
ch=input("Enter a character to be searched: ")
for i in str:
if i==ch:
count_A=count_A+1
print("No. of times the char",ch,"in the text file is",count_A)
f.close()
while True:
print("\t\tProgram to count the given characters in the text file")
print("1. To add lines to the text file: ")
print("2. To count the given character: ")
print("3. Exit")
choice=int(input("Enter the choice: "))
if choice==1:
write_txt()
elif choice==2:
read_txt()
else:
break
OUTPUT:
Program to count the given characters in the text file
1. To add lines to the text file
2. To count the given character
3. Exit
Enter the choice: 1
Enter a line: this is my first line
Do you want to add one more lines……(Y/N): y
Enter a line: this is my second line
Do you want to add one more lines……(Y/N): n
Program to count the given characters in the text file
1. To add lines to the text file
2. To count the given character
3. Exit
Enter the choice: 2
this is my first line
this is my second line
Enter a character to be searched: m
No. of times the char m in the text file is: 2
Program to count the given characters in the text file
1. To add lines to the text file
2. To count the given character
3. Exit
Enter the choice: 2
this is my first line
this is my second line
Enter a character to be searched: i
No. of times the char i in the text file is 7
Program to count the given characters in the text file
1. To add lines to the text file
2. To count the given character
3. Exit
Enter the choice: 3
Result:
Thus the given program has been executed successfully.
Prg. No.2 Program to count number of times the given word appears in the text file
AIM: To write a program to count number of times the given word appears in the text file.
def write_txt():
f=open("text1.txt",'w')
ans='Y'
while ans.upper()=='Y':
line=input("Enter a line: ")
f.write(line+"\n")
ans=input("Do you want to add one more lines......(Y/N): ")
f.close()
def read_word():
count_A=0
f=open("text1.txt","r")
str=f.read()
words=str.split()
print(words)
ch=input("Enter a word to be searched: ")
for i in words:
if i.upper()==ch.upper():
print(i)
count_A=count_A+1
print("No. of times the word",ch,"in the text file is",count_A)
f.close()
while True:
print("\t\tProgram to count the given word in the text file")
print("1. To add lines to the text file")
print("2. To count the given word")
print("3. Exit")
choice=int(input("Enter the choice: "))
if choice==1:
write_txt()
elif choice==2:
read_word()
else:
break
OUTPUT:
Program to count the given word in the text file
1. To add lines to the text file
2. To count the given word
3. Exit
Enter the choice: 1
Enter a line: hi we are learning text file
Do you want to add one more lines……(Y/N): y
Enter a line: reading and writing into a text file
Do you want to add one more lines……(Y/N): n
Program to count the given word in the text file
1. To add lines to the text file
2. To count the given word
3. Exit
Enter the choice: 2
['hi', 'we', 'are', 'learning', 'text', 'file', 'reading', 'and', 'writing', 'into', 'a', 'text', 'file']
Enter a word to be searched: text
No. of times the word text in the text file is 2
Result:
Thus the given program has been executed successfully.
Prg.No.3 Search an element and to find the largest & smallest element in a
list
Aim: To write a Menu driven program to search an element and to find the largest and smallest
number in a list
Program:
def largest(l1):
length=len(l1)
num=0
for i in range(length):
if(i==0 or l1[i]>num):
num=l1[i]
return num
def smallest(l1):
length=len(l1)
num=0
for i in range(length):
if(i==0 or l1[i]<num):
num=l1[i]
return num
def search(l1,s):
for i in range(len(l1)):
if l1[i]==s:
print(“Element found at position:”,i+1)
break
else:
print(“Element not found”)
list1=eval(input(“Enter the list(only numbers): “))
while(1):
print(“Menu”)
print(“1. Searching an element”)
print(“2. Largest number”)
print(“3.Smallest number”)
print(“4. Exit”)
ch=int(input(“Enter your choice”))
if ch==1:
s=int(input(“Enter the number to be searched”))
search(list1,s)
elif ch==2:
n=largest(list1)
print(“The largest value in a list=”,n)
elif ch==3:
n=smallest(list1)
print(“The smallest value in a list=”,n)
elif ch==4:
break
else:
print(“Wrong Choice”)
OUTPUT:
Enter the list(only numbers): [45,67,78,89,98]
Menu
1. Searching an element
2. Largest number
3.Smallest number
4. Exit
Enter your choice1
Enter the number to be searched67
Element found at position: 2
Menu
1. Searching an element
2. Largest number
3.Smallest number
4. Exit
Enter your choice2
The largest value in a list= 98
Menu
1. Searching an element
2. Largest number
3.Smallest number
4. Exit
Enter your choice3
The smallest value in a list= 45
Menu
1. Searching an element
2. Largest number
3.Smallest number
4. Exit
Enter your choice4
Result:
Thus the given program has been executed successfully
Prg.No. 4 Check the given number is Prime Number or Not
Aim: To write a program to check whether the given number is prime number or not
Program:
def prime(num):
f=0
for i in range(2,num):
if num%i==0:
print("Given number ",num," is not a prime
number”) f=1
break
if f==0:
print("The number ",num," is a prime number")
n=int(input("Enter a number"))
if n==1:
print("The given number is Neither prime nor Composite number")
else:
prime(n)
Output:
Enter a number 7
The number 7 is a prime number
Result:
Thus the given program has been executed successfully
Prg.No:5 Palindrome and count number of occurrence
Aim : To write a Menu driven program to accept a string and check for palindrome and count
number of occurrences of a character in a given string
Program:
def
palindrome(s):
rstr=s[::-1]
if(rstr==s):
print("The given string is palindrome")
else:
print("The given string is not a palindrome")
def count(s,chr1):
chr1=s.count(chr1)
return chr1
while(1):
print("Menu")
print("1.Palindrome")
print("2. Number of Occurrence")
print("3.Exit")
ch=int(input("Enter your choice:"))
if ch==1:
st=input("Enter the string:")
palindrome(st)
elif ch==2:
st=input("Enter the string :")
c=input("Enter a character to be count :")
print("The character ",c," is in ",st," is ",count(st,c))
elif ch==3:
break
else:
print("Wrong Choice")
Output:
1. Palindrome
2. Number of Occurrences
3. Exit
Enter your choice:2
Enter the string :hi hello how are you
Enter a character to be count :e
The character h is in hi hello how are you is 2
Result:
Thus the given program has been written and executed successfully
Prg.No.6 Text file - Display each words separated by ‘#’
Aim: To write a program to read a file and display the content with each word separated by ‘#
def create():
f=open("f1.txt","a")
print("Enter file content, press * to stop:")
while True:
str=input()
if str=="*":
break
f.write(str+'/n')
f.close()
def display():
f=open("f1.txt","r")
for line in f:
words=line.split()
for w in words:
print(w+"#",end="")
print()
f.close()
#main program
create()
display()
OUTPUT:
RESULT: Thus the given program has been written and executed successfully.
Prg.No:7 Random Number generator
Aim:
To write a program to generate random numbers between 1 and 6 (simulates a dice)
Program:
import random
def roll_dice():
print(random.randint(1,6))
print("""Welcome to my python random dice program!
To start press enter! Whenever you are over, type quit.""")
flag=True
while flag:
value=input(">")
if value.lower()=="quit":
flag=False
else:
print("Rolling dice. . .\nYour number is : ")
roll_dice()
Output:
Welcome to my python random dice program!
To start press enter! Whenever you are over, type quit.
>
Rolling dice....
Your number is :
4
>
Rolling dice....
Your number is :
6
>Quit
Result:
Thus the given program has been written and executed successfully.
Prg.No:8 Text file - Display no. of vowels, consonants, uppercase,
lowercase and other characters.
Aim: To write a program to read the content of a file and display total no. of vowels, consonants,
uppercase, lowercase and other characters.
Program: f=open("D:\\
content.txt") v,c,u,l,o=0,0,0,0,0
data=f.read()
for ch in data:
if ch.isalpha():
if ch.lower() in ['a','e','i','o','u']:
v=v+1
else:
c=c+1
if ch.isupper():
u=u+1
elif
ch.islower():
l=l+1
elif ch!=' ' and ch!='\n':
o=o+1
print("No. of Vowels:",v)
print("No. of Consonants:",c)
print("No. of Uppercase letters:",u)
print("No. of Lowercase letters:",l)
print("No. of Other characters:",o)
f.close()
Output:
No. of Vowels: 20
No. of Consonants: 34
No. of Uppercase letters: 4
No. of Lowercase letters: 50
No. of Other characters: 1
Result:
Thus the given program has been written and executed successfully.
Prg.No:9 Text file – Copy the text to another file
Aim: To program to read the content of file line by line and write it to another file except the
lines which have character ‘a’ in it
Program:
#Program to read the content of file line by line and write it to another file
f=open("D:\\file1.txt")
f1=open("D:\\file2.txt","w")
for l in f:
if 'a' not in l:
f1.write(l)
print("File copied successfully")
f.close()
f1.close()
Output:
File copied successfully
Result:
Thus the given program has been written and executed successfully.
Exp.no:10 Binary file - Search for a given roll number
Aim: To write a program to 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
Program:
import pickle
stud=[]
f=open("D:\\student.dat","wb")
ans='y'
while ans.lower()=='y':
roll=int(input("Enter Roll number:"))
name=input("Enter Name :")
stud.append([roll,name])
ans=input("Add any more record?(Y)")
pickle.dump(stud,f)
f.close()
f=open("D:\\student.dat","rb")
stud=[]
while True:
try:
stud=pickle.load(f)
except EOFError:
break
ans='y'
while ans.lower()=='y':
found=False
r=int(input("Enter Roll number to search :"))
for s in stud:
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):")
f.close()
Output:
Enter Roll number:10101
Enter Name :Aswin
Add any more record?(Y)y
Enter Roll number:10102
Enter Name :Ria
Add any more record?(Y)y
Enter Roll number:10103
Enter Name :Jeevan
Add any more record?(Y)n
Enter Roll number to search
:10105 ###Sorry! Roll number not
found## Search more ?(Y):y
Enter Roll number to search
:10103 ##Name is : Jeevan ##
Search more ?(Y):n
Result:
Thus the given program has been written and executed successfully
Exp.no:11 Binary file – Updation of marks
Aim:
To write a program to create a binary file with roll number, name and marks. Input a roll number
and update the marks
Program:
import pickle
stud=[]
f=open("D:\\student1.dat","wb")
ans='y'
while ans.lower()=='y':
roll=int(input("Enter Roll number:"))
name=input("Enter Name :")
marks=int(input("Enter marks :"))
stud.append([roll,name,marks])
ans=input("Add any more record?(Y)")
pickle.dump(stud,f)
f.close()
f=open("D:\\studen1.dat","rb")
stud=[]
while True:
try:
stud=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 stud:
if s[0]==r:
print("##Name is :",s[1],"##")
print("##Current marks :",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("Do u want to update more ?(Y):")
f.close()
Output:
Enter Roll number:10101
Enter Name :Aswin
Enter marks :89
Add any more record?(Y)y
Enter Roll number:10102
Enter Name :Ria
Enter marks :76
Add any more record?(Y)y
Enter Roll number:10103
Result:
Thus the given program has been written and executed successfully
Exp. No. 12.
CREATING A PYTHON PROGRAM TO IMPLEMENT MATHEMATICAL FUNCTIONS
AIM:
To write a Python program to implement python mathematical functions to find:
(i) To find Square of a Number.
(ii) To find Log of a Number(i.e. Log10)
(iii) To find Quad of a Number
SOURCE CODE:
Result:
Thus, the above Python program has been executed and the output is verified
Successfully.
Exp. No. 13
WRITE A PYTHON PROGRAM TO CREATE AND SEARCH EMPLOYEE’S RECORD
IN CSV FILE.
AIM:
To write a Python program Create a CSV file to store Empno, Name, Salary and search any Empno
and display Name, Salary and if not found display appropriate message.
SOURCE CODE:
Result:
Thus, the above Python program has been executed and the output is verified
successfully.
Exp.No. 14
WRITE A PYTHON PROGRAM TO IMPLEMENT STACK OPERATIONS(LIST)
AIM:
To write a Python program to implement Stack using a list data-structure, to perform
the following operations:
(i) To Push an object containing Doc_ID and Doc_name of doctors who specialize
in "ENT" to the stack.
(ii) To Pop the objects from the stack and display them.
(iii) To display the elements of the stack (after performing PUSH or POP)
SOURCE CODE:
Exp. No.15
CREATING A PYTHON PROGRAM TO IMPLEMENT STACK
OPERATIONS(Dictionary)
AIM:
To Write a program, with separate user-defined functions to perform the following
operations:
(i) To Create a function Push(Stk,D) Where Stack is an empty list and D is Dictionary of Items.
from this Dictionary Push the keys (name of the student) into a stack, where
the corresponding value (marks) is greater than 70.
(ii) To Create a Function Pop(Stk) , where Stk is a Stack implemented by a list of student
names. The function returns the items deleted from the stack.
(iii) To display the elements of the stack (after performing PUSH or POP).
Source Code:
Result:
Thus, the above Python program has been executed and the output is verified
Successfully.
OUTPUT:
Exp. No.22. Program to create a table “stu” with following specification using python
connectivity.
AIM: To write a Python Program to create a table “STU” with the following specification.
VARIABLE USED:
VARIABLE DATA TYPE PURPOSE OF VARIABLE
NAME
RNo Integer To get Rno from user
x String Iterative variable
ans String To confirm whether the user wants to continue
or not
Name String To get the Name from user.
Eng integer To get the English Maths from user.
Maths integer To get the Maths Marks from user.
CS integer To get the CS Mark from the user
Total Integer To get the sum of the marks given
Hobby String To get hobby from user
Native Sring To get the Native
T Tuple To store Rno, Name,Eng,Maths CS,Hobby and
Native
mycon To connect Database using interface
mycur Cursor object
FUNCTION USED:
FUNCTION NAME PURPOSE OF THE FUNCTION
Commit( ) To make the changes permanently
RESULT: The Program to create a table STU with the following specification using Python
Connectivity was written and executed successfully.
PROGRAM:
#Program to create a table stu with following specifications
import mysql.connector as mysc
myconn=mysc.connect(host="localhost",user="root",passwd="",database="school")
if myconn.is_connected():
print("Connected to database successfully")
else:
exit()
mycur=myconn.cursor()
mycur.execute('drop table stu')
mycur.execute('''create table stu (rno integer primary key, name varchar(10) not null,eng
integer,maths integer, cs integer,total integer,hobby varchar(10),native varchar(10))''')
mycur.execute('desc stu')
for x in mycur:
print(x)
ans='Y'
while ans.upper()=='Y':
rno=int(input("Enter roll no: "))
name=input("Enter name: ")
eng=int(input("Enter english marks: "))
maths=int(input("Enter maths marks: "))
cs=int(input("Enter cs marks: "))
hobby=input("Enter hobby: ")
native=input("Enter native place: ")
total=eng+maths+cs
T=(rno,name,eng,maths,cs,total,hobby,native)
mycur.execute('''insert into stu values(%s,'%s',%s,%s,%s,%s,'%s','%s')'''%T)
myconn.commit()
ans=input("Do you want to continue......(Y/N): ")
mycur.execute("select * from stu")
for x in mycur:
print(x)
myconn.close()
OUTPUT:
Connected to database successfully
('rno', 'int(11)', 'NO', 'PRI', None, '')
('name', 'varchar(10)', 'NO', '', None, '')
('eng', 'int(11)', 'YES', '', None, '')
('maths', 'int(11)', 'YES', '', None, '')
('cs', 'int(11)', 'YES', '', None, '')
('total', 'int(11)', 'YES', '', None, '')
('hobby', 'varchar(10)', 'YES', '', None, '')
('native', 'varchar(10)', 'YES', '', None, '')
Enter roll no: 12301
Enter name: aravind
Enter english marks: 80
Enter maths marks: 70
Enter cs marks: 80
Enter hobby: gardening
Enter native place: chitoor
Do you want to continue......(Y/N): y
Enter roll no: 12302
Enter name: akash
Enter english marks: 85
Enter maths marks: 75
Enter cs marks: 89
Enter hobby: painting
Enter native place: cudalore
Do you want to continue......(Y/N): y
Enter roll no: 12303
Enter name: benita
Enter english marks: 87
Enter maths marks: 65
Enter cs marks: 90
Enter hobby: carving
Enter native place: chennai
Do you want to continue......(Y/N): y
Enter roll no: 12304
Enter name: ganesh
Enter english marks: 90
Enter maths marks: 79
Enter cs marks: 99
Enter hobby: painting
Enter native place: chennai
Do you want to continue......(Y/N): y
Enter roll no: 12305
Enter name: seenath
Enter english marks: 92
Enter maths marks: 78
Enter cs marks: 69
Enter hobby: gardening
Enter native place: gwalior
Do you want to continue......(Y/N): n
(12301, 'aravind', 80, 70, 80, 230, 'gardening', 'chitoor')
(12302, 'akash', 85, 75, 89, 249, 'painting', 'cudalore')
(12303, 'benita', 87, 65, 90, 242, 'carving', 'chennai')
(12304, 'ganesh', 90, 79, 99, 268, 'painting', 'chennai')
(12305, 'seenath', 92, 78, 69, 239, 'gardening', 'gwalior')
Exp.No.23. Update the total by adding subject marks and increase the CS marks for the given roll
number using python connectivity.
AIM:
To write a Program to update the total by adding subject mark and increase the CS mark for
the given roll number using Python Connectivity.
VARIABLE USED:
VARIABLE DATA TYPE PURPOSE OF VARIABLE
NAME
x String Iterative variable
a Integer To get the roll no from whom the user wants to
increase CS
m Integer To get the marks to increased.
t Tuple To store m and a
mycon To connect Database using python connectivity
mycur Cursor object
FUNCTION USED:
FUNCTION NAME PURPOSE OF THE FUNCTION
Commit( ) To make the changes permanently
Exp.No.24
. Program to read student name and search whether the student name is in the table or
not using python connectivity .
AIM: To write a Program to read student name and search whether the student name is in the table
or not using python connectivity .
VARIABLE USED:
VARIABLE DATA TYPE PURPOSE OF VARIABLE
NAME
x String Iterative variable
a Integer To get the roll no from whom the user wants to
increase CS
m Integer To get the marks to increased.
t Tuple To store m and a
mycon To connect Database using python connectivity
mycur Cursor object
RESULT: Thus , the given program using Python Connectivity was written and executed
successfully.
PROGRAM:
RESULT: The Program to create a table STU with the following specification using Python
Connectivity was written and executed successfully.
OUTPUT:
Connected to database successfully
Program to search for the student present in student table
Displaying the STUDENT TABLE
(12301, 'aravind', 80, 70, 80, 230, 'gardening', 'chitoor')
(12302, 'akash', 85, 75, 89, 249, 'painting', 'cudalore')
(12303, 'benita', 87, 65, 90, 242, 'carving', 'chennai')
(12304, 'ganesh', 90, 79, 99, 268, 'painting', 'chennai')
(12305, 'seenath', 92, 78, 69, 239, 'gardening', 'gwalior')
Enter the name of the student to be searched: akash
No of records Matching: 1
(12302, 'akash', 85, 75, 89, 249, 'painting', 'cudalore')
do u want to continue the search......(Y/N): y
Enter the name of the student to be searched: ganesh
No of records Matching: 1
(12304, 'ganesh', 90, 79, 99, 268, 'painting', 'chennai')
do u want to continue the search......(Y/N): y
Enter the name of the student to be searched: santhosh
No of records Matching: 0
Record not found
do u want to continue the search......(Y/N): n
Exp.No.25.
Program to read student name and delete the record from the table using python
connectivity
AIM: To write a program to read student name and delete the record from the table using Python
Connectivity.
VARIABLE USED:
VARIABLE DATA TYPE PURPOSE OF VARIABLE
NAME
ans String To get the user choice
x String Iterative variable
a Integer To input the name to be deleted
t Tuple To store a
mycon To connect Database using python
connectivity
mycur Cursor object
PROGRAM: