Xii Cs Practical Record
Xii Cs Practical Record
COMPUTER SCIENCE
PRACTICAL FILE
SESSION 2021-22
NAME:
CLASS:
ROLL NO:
1
PRIMARILY I WOULD LIKE TO THANK GOD
FOR I BEING ABLE TO COMPLETE THIS
PRACTICAL FILE WITH SUCCESS THEN I
WOULD LIKE TO THANK MY COMPUTER
SCIENCE TEACHER MRS. SNEHA JETTI MS
FOR HER VALUEABLE GUIDENCE AND
SUGGESTIONS.
2
THIS IS TO CERTIFY THAT THIS PRACTICAL
____________________________________________________ OF
GUIDELINES.
SUBJECT TEACHER
1. Read a text file line by line and display each word separated by #.
Aim:
To Read a text file line by line and display each word separated by '#' in Python
Source Code:
filein = open("mydoc.txt",'r')
line =" "
while line:
line = filein.readline()
#print(line)
for w in line:
if w == ' ':
print('#',end = '')
else:
print(w,end = '')
filein.close()
PROGRAM - 2
Aim:
To Read first 5 characters from the file (“data.txt”) in Python
Source Code:
f = open("data.txt", 'r')
d = f.read(5)
print(d)
4
PROGRAM - 3
Aim:
To display first line from the file (“data.txt”) using readlines() in Python.
Source Code:
# Python code to
# demonstrate readlines()
# writing to file
file1 = open('myfile.txt', 'w')
file1.writelines(L)
file1.close()
# Using readlines()
file1 = open('myfile.txt', 'r')
Lines = file1.readlines()
count = 0
# Strips the newline character
for line in Lines:
count += 1
print("Line{}: {}".format(count, line.strip()))
5
PROGRAM - 4
4. Read a text file and display the number of vowels/ consonants/
uppercase/ lowercase characters in the file.
Aim:
To Read a text file and display the number of vowels/ consonants/ uppercase/
lowercase characters in the file in Python.
Source Code:
def cnt():
f=open("D:\\test2.txt","r")
cont=f.read()
print(cnt)
v=0
cons=0
l_c_l=0
u_c_l=0
for ch in cont:
if (ch.islower()):
l_c_l+=1
elif(ch.isupper()):
u_c_l+=1
ch=ch.lower()
if( ch in ['a','e','i','o','u']):
v+=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']):
cons+=1
f.close()
print("Vowels are : ",v)
print("consonants are : ",cons)
print("Lower case letters are : ",l_c_l)
print("Upper case letters are : ",u_c_l)
cnt()
6
PROGRAM - 5
5. Write a function in Python to count and display the total number
of words in a text file.
Aim:
To count and display the total number of words in a text file in Python.
Source Code:
def count_words():
file = open("notes.txt","r")
count = 0
data = file.read()
words = data.split()
for word in words:
count += 1
print("Total words are",count)
file.close()
count_words()
7
PROGRAM - 6
6. Remove all the lines that contain the character 'a' in a file and
write it to another file.
Aim:
To remove all the lines that contains the character ‘a’ in a file and writes it to
another file in Python
Source Code:
fo=open("hp.txt","w")
fo.write("Harry Potter")
fo.write("There is a difference in all harry potter books\nWe can see it
as harry grows\nthe books were written by J.K rowling ")
fo.close()
fo=open('hp.txt','r')
fi=open('writehp.txt','w')
l=fo.readlines()
for i in l:
if 'a' in i:
i=i.replace('a','')
fi.write(i)
fi.close()
fo.close()
8
PROGRAM - 7
7. Write a program that prompts the user to input a number and
prints its factorial. The factorial of an integer n is defined as n! =
1 x 2 x 3 x ... x n; if n > 0 = 1; if n = 0 For instance, 6! can be
calculated as 1 x 2 x 3 x 4 x 5 x 6.
Aim:
To write a program that prompts the user to input a number and prints its
factorial. The factorial of an integer n is defined as n! = 1 x 2 x 3 x ... x n; if n > 0 =
1; if n = 0 For instance, 6! can be calculated as 1 x 2 x 3 x 4 x 5 x 6 in Python.
Source Code:
num = int(input("Enter a positive number: "))
fact=1
i=num
while i>1:
fact=fact*i
i=i-1
print("Factorial of",num,"is",fact)
9
PROGRAM - 8
8. Suppose a, b, and c denote the lengths of the sides of a triangle.
Then the area of the triangle can be calculated using the formula:
where
Write a program that asks the user to input the length of sides of
the triangle and print the area.
Aim:
To find area of the triangle by asking the lengths of the sides of a triangle from the
users and by using the formula and print the area in Python
Source Code:
import math
side1= float(input("Enter length of side 1: "))
side2= float(input("Enter length of side 2: "))
side3= float(input("Enter length of side 3: "))
10
PROGRAM - 9
9. Write a function to search and display details of student whose
rollno is '1005' from the binary file student.dat having structure
[rollno, name, class and fees].
Aim:
To search and display details of student whose rollno is '1005' from the binary file
student.dat having structure [rollno, name, class and fees] in Python
Source Code:
def search():
file = open("student.dat","rb")
try:
while True:
record = pickle.load(file)
if record[0] == 1005:
print(record)
except EOFError:
pass
file.close()
11
PROGRAM - 10
10. Write a random number generator that generates random
numbers between 1 and 6 (simulates a dice).
Aim:
To generates random numbers between 1 and 6 (simulates a dice). Using random
number generator in Python
Source Code:
import random
def rolladice():
counter = 0
myList = []
while (counter) < 6:
randomNumber = random.randint(1,6)
myList.append(randomNumber)
counter = counter + 1
if (counter)>=6:
pass
else:
return myList
n=1
while(n==1)
n = int(input("Enter 1 to roll a dice and get a random number:"))
print(rolladice())
12
PROGRAM - 11
11. A binary file "Book.dat" has structure [BookNo, Book_Name,
Author, Price].
Aim:
To open a binary file "Book.dat" has structure [BookNo, Book_Name, Author, Price]
write a user defined function createFile() to input data for a record and add to
Book.dat and write a function countRec(Author) which accepts the Author name
as parameter and count and return number of books by the given Author are
stored in the binary file "Book.dat" in Python.
Source Code:
import pickle
def createFile():
file = open("book.dat","ab")
BookNo = int(input("Enter book number: "))
Book_Name = input("Enter book Name: ")
Author =input("Enter author: ")
Price = int(input("Enter price: "))
record = [BookNo, Book_Name, Author, Price]
pickle.dump(record, file)
file.close()
def countRec(Author):
file = open("book.dat","rb")
count = 0
13
try:
while True:
record = pickle.load(file)
if record[2]==Author:
count+=1
except EOFError:
pass
return count
file.close()
14
PROGRAM - 12
Aim:
To write a function find_max that accepts three numbers as arguments and returns
the largest number among three. Write another function main, in main() function
accept three numbers from user and call find_max in Python
Source Code:
15
PROGRAM - 13
13. Write a program to know the cursor position and print the
text according to below-given specifications:
Aim:
To cursor position and print the text according to below-given specifications:
Source Code:
def program9():
f = open("merge.txt","r")
print(f.tell())
f.seek(4,0)
print(f.read(5))
f.seek(10,0)
print(f.tell())
print(f.seek(7,0))
print(f.read(10))
program9()
16
PROGRAM - 14
Aim:
To perform the basic arithmetic operations in a menu-driven program with
different functions. The output should be like this:
Source Code:
def main():
print('+ for Addition')
print('- for Subtraction')
print('* for Multiplication')
print('/ for Division')
ch = input("Enter your choice:")
if ch=='+':
x=int(input("Enter value of a:"))
y=int(input("Enter value of b:"))
print("Addition:",add(x,y))
elif ch=='-':
x=int(input("Enter value of a:"))
y=int(input("Enter value of b:"))
print("Subtraction:",sub(x,y))
elif ch=='*':
x=int(input("Enter value of a:"))
17
y=int(input("Enter value of b:"))
print("Multiplication",mul(x,y))
elif ch=='/':
x=int(input("Enter value of a:"))
y=int(input("Enter value of b:"))
print("Division",div(x,y))
else:
print("Invalid character")
def add(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def div(a,b):
return a/b
main()
18
PROGRAM - 15
15. 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.
Aim:
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
in Python programming.
Source Code:
#Practical Program 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.
import pickle
import sys
dict={}
def write_in_file():
file=open("D:\\stud2.dat","ab") #a-append,b-binary
no=int(input("ENTER NO OF STUDENTS: "))
for i in range(no):
print("Enter details of student ", i+1)
dict["roll"]=int(input("Enter roll number: "))
dict["name"]=input("enter the name: ")
pickle.dump(dict,file) #dump-to write in student file
file.close()
def display():
#read from file and display
file=open("D:\\stud2.dat","rb") #r-read,b-binary
try:
while True:
stud=pickle.load(file) #write to the file
print(stud)
except EOFError:
pass
file.close()
19
def search():
file=open("D:\\stud2.dat","rb") #r-read,b-binary
r=int(input("enter the rollno to search: "))
found=0
try:
while True:
data=pickle.load(file) #read from file
if data["roll"]==r:
print("The rollno =",r," record found")
print(data)
found=1
break
except EOFError:
pass
if found==0:
print("The rollno =",r," record is not found")
file.close()
#main program
#Prepared by Ramesha K S
while True:
print("MENU \n 1-Write in a file \n 2-display ")
print(" 3-search\n 4-exit \n")
ch=int(input("Enter your choice = "))
if ch==1:
write_in_file()
if ch==2:
display()
if ch==3:
search()
if ch==4:
print(" Thank you ")
sys.exit()
****************
20