0% found this document useful (0 votes)
342 views

Computer Practical Term1

This document contains a computer practical project submission for a student named Nandini Kesarwani. It includes a certificate signed by internal and external examiners certifying that the student successfully completed the practicals. It also includes acknowledgements and solutions to 14 questions involving various Python programming tasks related to files, strings, functions and CSV files.

Uploaded by

Ashree Kesarwani
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
342 views

Computer Practical Term1

This document contains a computer practical project submission for a student named Nandini Kesarwani. It includes a certificate signed by internal and external examiners certifying that the student successfully completed the practicals. It also includes acknowledgements and solutions to 14 questions involving various Python programming tasks related to files, strings, functions and CSV files.

Uploaded by

Ashree Kesarwani
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

EWING CHRISTIAN

PUBLIC SCHOOL
PRAYAGRAJ.

COMPUTER PRACTICAL

SUBMITTED TO : SUBMITTED BY :
Mr. KISHAN KESARWANI Nandini kesarwani
(23707525)

Certificate
This is to certify that “NANDINI KESARWANI ”,
student of class XII-A1 has successfully completed the
practicals of computer science for the academic
session 2021-2022.

This project is absolutely genuine and does not indulge


in any plagiarism of any kind. The references taken in
the activities have been declared at the end of the
project.

_____________________
_____________________
Internal Examiner’s Signature External Examiner’s
signature

Acknowledgement
I would like to express my thankfulness towards my
subject teacher Mr. Kishan Kesarwani for guiding me
immensely through the course of this project.

Secondly, I would also like to express my thanks


to my parents for their motivation and support. I must
also thanks to all my friends for their timely help.

Last but not the least, I would like to thank all those
who had helped me directly or indirectly towards the
completion of this project.

-NANDINI KESARWANI

TERM-1

Q1) Read a text file line by line and display each word separated by a #.
Sol) file=open("file.txt",'r')
content=file.readlines()
for line in content:
words=line.split()
for word in words:
print(word+"#",end='')
print(" ")
Q2)Read a text file and display the number of vowels/consonants/uppercase/lowercase
characters in the file.
Sol) def cnt():
f=open("school.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()
Q3)Remove all the lines that contain the letter “a” in a file and write to another file.
Sol) fo=open("fun.txt",'w')
fo.write("Amusement Park")
fo.write("Going to amusement park is a lot of fun as we can enjoy various rides,
have snacks and spend our whole day enjoying there.")
fo.close()
fo=open("fun.txt",'r')
fi=open("enjoy.txt",'w')
l=fo.readlines()
for i in l:
if 'a'in i:

i=i.replace('a','')
fi.write(i)
print(i)
fi.close()
fo.close()

Q4) 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.
Sol) import pickle
#creating the file and writing the data
f=open("records.dat","wb")
pickle.dump(["Wakil",1],f)
pickle.dump(["Tanish",2],f)
pickle.dump(["Priyashi",3],f)
pickle.dump(["Kahupriya",4],f)
pickle.dump(["Aaheli",5],f)
f.close()
#opening the file to read contents
f=open("records.dat","rb")
n=int(input("Enter the Roll Number:"))
flag=False
while True:
try:
x=pickle.load(f)

if x[1]==n:
print("Name:",x[0])

flag=True
except EOFError:
break
if flag==False:
print("This Roll Number does not exist")

Q5) Create a binary file with roll number, name and marks. Input a roll number and
update the marks.
Sol) import pickle
#creating the file and writing the data
f=open("records.dat","wb")
#list index 0=roll number
#list index 1=name
#list index 2=marks
pickle.dump([1,"Wakil",90],f)
pickle.dump([2,"Tanish",80],f)
pickle.dump([3,"Priyashi",90],f)
pickle.dump([4,"Kanupriya",80],f)
pickle.dump([5,"Ashutosh",85],f)
f.close()
#opening the file to read contents
f=open("records.dat","rb")
roll=int(input("Enter the Roll Number:"))
marks=float(input("Enter the updated mark:"))

list=[]#empty list
flag=False #turns to True if record if found.
while True:

try:
record=pickle.load(f)
list.append(record)
except EOFError:
break
f.close()
#reopening the file to update the marks
f=open("records.dat","wb")
for rec in list:
if rec[0]==roll:
rec[2]=marks
pickle.dump(rec,f)
print("Record updated successfully")
flag=True
else:
pickle.dump(rec,f)
f.close()
if flag==False:
print("This roll number does not exist")

Q6) Write a random number generator that generates random numbers between 1 and
6 (stimulates a dice).
Sol) def random():

import random
s=random.randint(1,6)
return s
while True:

ch=int(input("Enter 1 to Roll the dice and any other key to exist..."))


if ch==1:
print('Dice:',random())
else:
print("Game Over")
break
Q7) Create a CSV file by entering user-id and password, read and search the password
for given user-id.
Sol) import csv
#User-id and password list
List=[["user1","password1"],
["user2","password2"],
["user3","password3"],
["user4","password4"],
["user5","password5"]]
#opening the file to write the records
f1=open("UserInformation.csv","w",newline="\n")
writer=csv.writer(f1)
writer.writerows(List)
f1.close()
#opening the file to read the records
f2=open("Userinformation.csv","r")

rows=csv.reader(f2)
userId=input("Enter the user-id:")
flag=True
for record in rows:
if record[0]==userId:
print("The password is:",record[1])
flag=False
break
if flag:
print("User-id not found")

Q8) Write a function that receives two string arguments and checks whether they are
same length strings ( returns True in this case otherwise False).
Sol) def chr(a,b):
print(len(a)==len(b))
first=input("Enter a number=")
second=input("Enter second number=")
chr(first,second)

Q9) Program to calculate simple interest using a function interest( ) that can receive
principal amount, time and rate and returns calculated simple interest. Do specify
default values for rate and time as 10% and 2 years respectively.
Sol) def interest(principal, time=2, rate=0.10):
return principal*rate*time
#_main_

prin=float(input("Enter principal amount:"))


print("Simple interest with default ROI and time value is:")
si1=interest(prin)
print("Rs.",si1)
roi=float(input("Enter rate of interest(ROI):"))
time=int(input("Enter time in years:"))

print("Simple interest with your provided ROI and time value is:")
si2=interest(prin, time,roi/100)
print("Rs.",si2)
Q10) Write a program that inputs a main string and then creates an encrypted string by
embedding a short symbol based string after each character. The program should also
be able to produce the decrypted string from encrypted string.
Sol) def encrypt(sttr,enkey):
return enkey.join(sttr)
def decrypt(sttr,enkey):
return sttr.split(enkey)
#_main_
mainstring=input("Enter main string:")
encryptstr=input("Enter encryption key:")
enStr= encrypt(mainstring,encryptstr)
delst=decrypt(enStr,encryptstr)
#delst is in the form of a list,converting it to string below
deStr="".join(delst)
print("The encrypted string is",enStr)
print("String after decryption is:",deStr)

Q11) Write a function in Python that counts the number of “Me” or “My” words
present in a text file “STORY.TXT”. If the “STORY.TXT” contents are as follows:
My first book
was Me and
My family. It

gave Me
chance to be
known to the
world.
The output of the function should be:-
Count of Me/My in file:4
Sol) def countMeMy():
file=open("STORY.TXT")
content=file.read()
result=content.split()
count=0
for i in result:
if i=="Me"or i=="My":
count+=1
return count
print("Count of Me/My in file:",countMeMy())

Q12) 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 the number of students scoring above 75%.

Sol) import pickle


def createfile():
Admission_number=int(input("Enter admission number:"))
Name=input("Enter student name:")
Percentage=float(input("Enter percentage:"))
l=[Admission_number, Name, Percentage]

f=open("Student.dat","ab")
pickle.dump(l,f)
f.close()
createfile()
def countrec():
fobj=open("Student.dat","rb")
num=0
try:
while True:
rec=pickle.load(fobj)
if rec[2]>75:
print(rec[0],rec[1],rec[2],sep="\t")
num=num+1
except:
fobj.close()
return num
countrec()

Q13) Write a program to create a CSV file by suppressing EOL translation.

Sol) import csv


fh=open("Employee.csv","w",newline='')
ewriter=csv.writer(fh)
empdata=[
['Empno','Name','Designation','Salary'],
[1001,'Trupti','Manager',56000],
[1002,'Raziya','Manager',55900],

[1003,'Simran','Manager',55800],
[1004,'Silviya','Analyst',35000],
[1005,'Suji','Clerk',25000]
]
ewriter.writerows(empdata)
print("File successfully created")
fh.close()

Q14) Write a program to create a csv file to store data (Roll No., Name, Marks).
Obtain data from user and write 5 records into the file.
Sol) import csv
fh=open("Student.csv","w")
stuwriter=csv.writer(fh)
stuwriter.writerow(['Rollno', 'Name', 'Marks'])
for i in range(5):
print("student record",(i+1))
Rollno=int(input("Enter Rollno:"))
name=input("Enter name:")
marks=float(input("Enter marks:"))

sturec=[Rollno, name, marks]


stuwriter.writerow(sturec)
fh.close()

Q15. Write a program that inputs a real number and converts it to nearest integer
using two different built-in-functions. It also displays the given number rounded off to
3 places after decimal.
Sol)
num=float(input("Enter a real number:"))
tnum=int(num)
rnum=round(num)
print("Number", num,"converted to integer in 2 ways as",tnum,"and",rnum)
rnum2=round(num,3)
print(num,"rounded off to 3 places after decimal is", rnum2)

You might also like