CS Practicals Xii 2021 22
CS Practicals Xii 2021 22
AIM – Python program to read a text file line by line and display each
word separated by a #.
VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
st String To store contents of text file
data List To store words separated by # in the list
wrd String To store individual words of list
CONTENT OF ARTICLE.TXT
Artificial#intelligence#algorithms#are#designed#to
make#decisions,#often#using#real-
time#data.#They#are#unlike#passive#machines#that#are#capable#only
#of#mechanical#or#predetermined#responses.
CODE
myfile = open('ARTICLE.TXT','r')
st = myfile.read()
data = st.split('#')
for wrd in data:
print(wrd, end=' ')
myfile.close()
OUTPUT
Artificial intelligence algorithms are designed to make decisions, often
using real-time data. They are unlike passive machines that are capable
only of mechanical or predetermined responses.
PRACTICAL 2 (2020-21)
AIM – Read a text file and display the number of vowels/ consonants /
uppercase / lowercase characters in the file.
VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
St String To store contents of text file
Ch String To store individual characters from the
string
vow int To store count of vowels
con int To store count of consonants
upp int To store count of uppercase characters
low int To store count of lower case characters
oth int To store count of other characters
~1~
CONTENT OF PYTHON.TXT
What is Python? #EXECUTIVE SUMMARY@2020!#
Python is an interpreted, object-oriented, high-level programming
language with dynamic semantics. It is more efficient than other 3rd
and 4th GENERATION LANGUAGES.
CODE
myfile = open('PYTHON.TXT','r')
vow = con = upp = low = oth = 0
st = myfile.read()
for ch in st:
if ch.isalpha():
if ch.isupper():
upp += 1
if ch.islower():
low += 1
if ch.upper() in 'AEIOU':
vow += 1
else:
con += 1
else:
oth += 1
print('Total Uppercase characters =',upp)
print('Total Lowercase characters =',low)
print('Total vowels =',vow)
print('Total consonants =',con)
print('Other characters =',oth)
myfile.close()
OUTPUT
Total Uppercase characters = 39
Total Lowercase characters = 124
Total vowels = 60
Total consonants = 103
Other characters = 43
PRACTICAL 3 (2020-21)
AIM – Python program to copy all the lines that contain the character
'a' from a file and write them to another file.
VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
data List To store contents of text file as list of
strings(lines)
line String To store individual lines from the list data
~2~
CONTENTS OF FARMER.TXT
A farmer looking for a source of water for his farm.
He bought one well from his neighbour.
The neighbour was cunning.
I sold the well to you.
The farmer didn’t know what to do.
So he went to Birbal.
CODE
myfile = open('FARMER.TXT','r')
tofile = open('OUTFILE.TXT', 'w')
data = myfile.readlines()
for line in data:
if 'a' in line:
tofile.write(line)
myfile.close()
tofile.close()
OUTPUT
CONTENTS OF OUTFILE.TXT
A farmer looking for a source of water for his farm.
The neighbour was cunning.
The farmer didn’t know what to do.
So he went to Birbal.
PRACTICAL 4 (2020-21)
AIM – Python program to read a file and display all the lines in reverse
order.
VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
data List To store contents of text file as list of
strings(lines)
line String To store individual lines from the list data
c String To store individual character of line
CONTENTS OF STORY.TXT
Ten pundits (holy men) went to the Ganga to take a dip in the river.
They held each other’s hands as they took dips thrice.
When they came up the third time, they were not holding hands.
“Let’s make sure all of us have come out of the river safely.”
I will count.
~3~
CODE
myfile = open('STORY.TXT','r')
data = myfile.readlines()
for line in data:
for c in range(len(line)-2,-1,-1):
print(line[c], end='')
print()
myfile.close()
OUTPUT
.revir eht ni pid a ekat ot agnaG eht ot tnew )nem yloh( stidnup neT
.ecirht spid koot yeht sa sdnah s'rehto hcae dleh yehT
.sdnah gnidloh ton erew yeht ,emit driht eht pu emac yeht nehW
".ylefas revir eht fo tuo emoc evah su fo lla erus ekam s'teL"
.tnuoc lliw I
PRACTICAL 5 (2020-21)
AIM – Python program to read a text file and display all the words
which starts with c or C.
VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
st String To store contents of text file as string
data List To store individual words from the string
wrd String To store individual words(elements) from
data
CONTENTS OF STORY2.TXT
Ten pundits (holy men) went to the Ganga to take a dip in the river.
They held each other’s hands as they took dips thrice.
When they came up the third time, they were not holding hands.
“Let’s make sure all of us have come out of the river safely.”
I will COUNT.
CODE
myfile = open('STORY2.TXT','r')
st = myfile.read()
data = st.split()
for wrd in data:
if wrd[0] == 'c' or wrd[0] == 'C':
print(wrd, end=' ')
myfile.close()
OUTPUT
came come COUNT.
~4~
PRACTICAL 6 (2020-21)
AIM – Python program to read a text file, creates a new file where each
character's case is inverted.
VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
data String To store the contents of text file in a string
c String To store individual characters(elements)
from data
CONTENTS OF STORY3.TXT
Ten PUNDITS (holy men) went to the GANGA to take a dip in the river.
THEY HELD EACH OTHER'S HANDS AS THEY TOOK DIPS THRICE.
When they came up the third time, they were not HOLDING Hands.
"Let's make SURE ALL of us have come out of the RIVER Safely."
I will COUNT.
CODE
file = open('STORY3.TXT','r')
outfile = open('NEWFILE.TXT','w')
data = file.read()
for c in data:
if c.isupper():
outfile.write(c.lower())
else:
outfile.write(c.upper())
file.close()
outfile.close()
OUTPUT
CONTENTS OF NEW FILE
tEN pundits (HOLY MEN) WENT TO THE ganga TO TAKE A DIP IN THE
RIVER.
they held each other's hands as they took dips thrice.
wHEN THEY CAME UP THE THIRD TIME, THEY WERE NOT holding
hANDS.
"lET'S MAKE sure all OF US HAVE COME OUT OF THE river sAFELY."
i WILL count.
~5~
PRACTICAL 7 (2020-21)
AIM – Program to read a text file and display the total number of lines
words and characters.
Also Count and Display all words which starts with t or T
VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
filename String To accept the file name to be opened from
the user.
data List To store individual words from the string
lines Int To store count of lines
words Int To store count of words
chars Int To store count of characters
wrd String To store individual words
count Int To store count of words that starts with t or
T
CONTENTS OF STORY3.TXT
Ten PUNDITS (holy men) went to the GANGA to take a dip in the river.
THEY HELD EACH OTHER'S HANDS AS THEY TOOK DIPS THRICE.
When they came up the third time, they were not HOLDING Hands.
"Let's make SURE ALL of us have come out of the RIVER Safely."
I will COUNT.
CODE
filename =input('Enter the file to open : ')
myfile = open(filename,'r')
data = myfile.read()
lines = len(data.split('\n'))
words = len(data.split(' '))
chars = len(data)
print('Total lines =',lines)
print('Total words =', words)
print('Total characters =',chars)
print('\nList of words that starts with t or T')
count = 0
for wrd in data.split(' '):
if wrd[0] == 't' or wrd[0] == 'T':
count += 1
print(wrd, end=' ')
print("\nTotal words that starts with 't' or 'T' = ", count)
OUTPUT
Enter the file to open : STORY3.TXT
Total lines = 6
Total words = 51
Total characters = 266
~6~
List of words that starts with t or T
Ten to the to take the THEY TOOK THRICE. they the third time, they
the
Total words that starts with 't' or 'T' = 15
PRACTICAL 8 (2020-21)
AIM – Develop a Python program that accepts Roll Number, Name and
Percentage of multiple students and save the information into a binary
file. After accepting all records display the contents of binary file on
the screen
VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
fil File object File object associated to binary file
stufile.dat for writing purpose.
stu Dictionary To store roll number, name and percentage
of a student.
rno int Dictionary element to store roll number
name String Dictionary element to store name of student
percent float Dictionary element to store percentage of
student
Rn int Variable to store roll number
Nm String Variable to store name of student
Pr float Variable to store percentage of student
CODE
import pickle
fil = open('stufile.dat', 'wb')
choice = 'Y'
stu = { }
while choice.upper() == 'Y':
rn = int(input('Enter roll number : '))
nm = input('Enter student name : ')
pr = float(input('Enter percentage : '))
~7~
choice = input('Want to enter more data y/n : ')
print('Data written into binary file!!!!')
fil.close()
OUTPUT
Enter roll number : 101
Enter student name : Anand
Enter percentage : 78.5
Want to enter more data y/n : y
Enter roll number : 102
Enter student name : Manish Mishra
Enter percentage : 88.1
Want to enter more data y/n : n
Data written into binary file!!!!
Contents of stufile.dat
{'rno': 101, 'name': 'Anand', 'percent': 78.5}
{'rno': 102, 'name': 'Manish Mishra', 'percent': 88.1}
PRACTICAL 9 (2020-21)
AIM - Develop a python program to accept Employee Number,
Employee Name, Salary and Department into a List, and save the
details of employees into binary file named COMPANY.DAT. After
creating the binary file accept employee number from the user and
search it in the binary file and display the information of the employee.
VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
fil File object File object associated to binary file
COMPANY.DAT for both reading and writing
purpose.
emp List To store employee number, name, salary
and department
~8~
Rn Int Dictionary element to store roll number
Name String Dictionary element to store name of student
Salary float Dictionary element to store percentage of
student
En Int Variable to store employee number
Nm String Variable to store name of employee
Sal Float Variable to store salary of employee
Dep String Variable to store department of employee
CODE
import pickle
fil = open('COMPANY.DAT', 'wb+') #Binary file opened for both reading and writing
choice = 'Y'
emp = [ ]
while choice.upper() == 'Y':
en = int(input('Enter employee number : '))
nm = input('Enter employee name : ')
sal = float(input('Enter employee salary : '))
dep = input("Enter employee's department : ")
try:
print('Details of employee')
while True:
emp = pickle.load(fil)
if emp[0] == en:
print(emp)
found = True
except:
if not found:
print('Record NOT found')
fil.close()
~9~
OUTPUT
Enter employee number : 101
Enter employee name : Rima Sen
Enter employee salary : 50000
Enter employee's department : Administration
Want to enter more data y/n : y
Enter employee number : 104
Enter employee name : Jagdish Mishra
Enter employee salary : 30000
Enter employee's department : Sales
Want to enter more data y/n : y
Enter employee number : 108
Enter employee name : Om Lakhan
Enter employee salary : 40000
Enter employee's department : Sales
Want to enter more data y/n : n
Data written into binary file!!!!
PRACTICAL 10 (2020-21)
AIM – A binary file “Books.dat” has structure [BookNo, Book_Name,
Author, Price].
i. Write a user defined function CreateFile() to input data for a
record and add to Books.dat .
ii. Write a function CountRec(Author) in Python which accepts the
Author name as parameter and count and return number of
books by the given Author are stored in the binary file
“Books.dat”
Develop Python code to create and test the above user defined
functions.
VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
fil File object File object associated to binary file
BOOKS.DAT
Bn Int Variable to store book number
Nm String Variable to store name of book
Price Float Variable to store price of book
Au String Variable to store author of book
choice String To accept user’s choice
book List To store details of one book
~ 10 ~
Author String Function parameter to receive author’s
name
CODE
def CreateFile():
import pickle
fil = open('BOOKS.DAT', 'wb') #Binary file opened for writing
choice = 'Y'
while choice.upper() == 'Y':
bn = int(input('Enter book number : '))
nm = input('Enter book name : ').upper()
au = input('Enter author name : ').upper()
price = float(input('Enter price of the book : '))
def CountRec(Author):
import pickle
fil = open('BOOKS.DAT', 'rb') #Binary file opened for reading
book = [ ]
tot = 0
try:
while True:
book = pickle.load(fil)
if book[2] == Author:
tot = tot + 1
except:
fil.close()
return tot
CreateFile()
Author = input('Enter auther name to search and count : ').upper()
print('Total books of author',Author, 'is/are',CountRec(Author))
OUTPUT
Enter book number : 111
Enter book name : C++ Programming
Enter author name : E Balaguruswamy
Enter price of the book : 400
~ 11 ~
Want to enter more data y/n : y
Enter book number : 112
Enter book name : C Programming
Enter author name : E Balaguruswamy
Enter price of the book : 350
Want to enter more data y/n : y
Enter book number : 115
Enter book name : Learn Python
Enter author name : S John
Enter price of the book : 500
Want to enter more data y/n : y
Enter book number : 118
Enter book name : Computer Basics
Enter author name : P K Sinha
Enter price of the book : 288
Want to enter more data y/n : n
Data written into binary file!!!!
PRACTICAL 11 (2020-21)
AIM – Develop a Python program to create a binary file “STUDENT.DAT”
has structure (admission_number, Name, Percentage). Write a function
countrec() in Python that would read contents of the file
“STUDENT.DAT” and display the details of those students whose
percentage is above 75. Also display number of total students and
number of students scoring above 75%.
VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
fil File object File object associated to binary file
STUDENT.DAT
admno Int Variable to store admission number
nm String Variable to store name of student
percent Float Variable to store percentage of student
choice string To accept user’s choice
stu Tuple To store details of one student
tot Int To store total number of students
dis Int To store number of students having more
than 75%
CODE
~ 12 ~
def CreateFile():
import pickle
fil = open('STUDENT.DAT', 'wb') #Binary file opened for writing
choice = 'Y'
while choice.upper() == 'Y':
admno = int(input('Enter admission number : '))
nm = input('Enter name : ')
percent = float(input('Enter percentage : '))
def CountRec():
import pickle
fil = open('STUDENT.DAT', 'rb') #Binary file opened for reading
stu = ()
tot = dis = 0
try:
print('Details of students having percentage more than 75 ')
while True:
stu = pickle.load(fil)
tot = tot + 1
if stu[2] > 75.0:
print(stu)
dis = dis + 1
except:
fil.close()
print('Total students = ', tot)
print('Number of students securing more than 75% = ', dis)
CreateFile()
CountRec()
OUTPUT
Enter admission number : 111
Enter name : Rahul K
Enter percentage : 65.8
Want to enter more data y/n : y
Enter admission number : 112
Enter name : Jaya Kumari
Enter percentage : 78
Want to enter more data y/n : y
~ 13 ~
Enter admission number : 115
Enter name : Taposh Kumar
Enter percentage : 55.5
Want to enter more data y/n : y
Enter admission number : 118
Enter name : Ram Singh
Enter percentage : 98.8
Want to enter more data y/n : n
Data written into binary file!!!!
Total students = 4
Number of students securing more than 75% = 2
PRACTICAL 12 (2020-21)
AIM – A binary file stufile.dat contains records of students in the
structure {'rno':roll Number,'name':Name of student,
'percent':Percentage of student}. Develop a python program to
change/update the details of a particular student based on Roll Number
in the binary file.
VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
fil File object File object associated to binary file
stufile.dat. Opened for reading and writing.
rn Int Variable to store roll number
rno Int Dictionary key to store roll number
name String Dictionary key to store name of student
percent Float Dictionary key to store percentage of student
pos int To store position of file pointer
stu Dictionary To store details of one student
nm String To store new name of student
pr Float To store new percentage of student
found Boolean To store status of record, whether found or
not.
CODE
import pickle
stu = { }
fil = open('stufile.dat','rb+') #File opened for reading and writing both
~ 14 ~
rn = int(input('Enter roll no of student whose record you want to update
: '))
found = False
#Search the dictionary having above roll number in the binary file
try:
while True:
pos = fil.tell()
stu = pickle.load(fil)
if stu['rno'] == rn:
print('Name of student : ',stu['name'])
nm = input('Enter modified name of student : ')
stu['name'] = nm
print('Percentage of student : ',stu['percent'])
pr = float(input('Enter modified percent : '))
stu['percent'] = pr
found = True
except:
if found:
print('Record updated !!!')
else:
print('Sorry!!!Record not found')
fil.close()
OUTPUT
Enter roll no of student whose record you want to update : 102
Name of student : Manish Mishra
Enter modified name of student : Manisha Mehta
Percentage of student : 88.1
Enter modified percent : 98.8
Record updated !!!
PRACTICAL 13 (2020-21)
AIM – Develop a Python program to create csv file named EMP.csv to
store employee no, name and salary of more than one employees.
VARIABLE DESCRIPTION
~ 15 ~
Variable/Object Data Type Description
Name
fh File object File object associated to csv file EMP.csv
Opened for writing.
eno Int Variable to store employee number
en String Variable to store name of employee
sl Int Variable to store employee salary
choice String To store choice
erec List To store details of one employee
CODE
import csv
fh = open('EMP.csv','w', newline='')
choice = 'Y'
while choice.upper()=='Y':
eno = int(input('Enter employee number : '))
en = input('Enter employee name : ')
sl = int(input('Enter salary : '))
erec = [eno, en, sl]
ewriter.writerow(erec) #or ewriter.writerow([eno,en, sl])
choice = input('Want to enter more records y/n : ')
fh.close()
OUTPUT
Contents of EMP.csv file
PRACTICAL 19 (2020-21)
AIM – Write a python program to implement a function showPrime(n)
that accepts n as parameter and display prime numbers upto n, using
another function isPrime(i) that checks whether i is prime or not.
VARIABLE DESCRIPTION
~ 16 ~
Variable/Object Data Type Description
Name
n Int To read value of n (Number)
p Bool To check whether number is prime
d Int To store an integer
CODE
def isPrime(n):
p=True
d=2
while d<=pow(n,0.5) and p:
if n%d==0:
p=False
else: d+=1
return p
def showPrime(n):
print("Prime numbers in the range 1 to",n,"are: ")
for i in range(2,n+1):
if isPrime(i): #Calling isPrime() from showPrime()
print(i,end=" ")
OUTPUT
To display prime numbers from 1 to n:
Enter the value of n: 25
Prime numbers in the range 1 to 25 are:
2 3 5 7 11 13 17 19 23
PRACTICAL 20 (2020-21)
AIM – Write a python program using function to accept a list as
parameter and multiply all the odd elements by 5.
VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
lst List To read list of number.
i Int To control the loop
CODE
def displaylist(lst):
for i in range(0,len(lst)):
~ 17 ~
if lst[i]%2==1:
lst[i]=lst[i]*5
print("New List in function call",lst)
lst=eval(input("Enter the list : "))
print("List before the function call : ",lst)
displaylist(lst)
print("List after the function call : ",lst)
OUTPUT
Enter the list : [2, 4, 3, 5, 8, 7]
List before the function call : [2, 4, 3, 5, 8, 7]
New List in function call [2, 4, 15, 25, 8, 35]
List after the function call : [2, 4, 15, 25, 8, 35]
~ 18 ~