0% found this document useful (0 votes)
216 views20 pages

Xii SC Practical Assignment

The document contains instructions and source code for 9 programming assignments on working with files in Python. The assignments cover: 1) Reading a text file line by line and printing each word separated by #. 2) Reading a text file and counting vowels, consonants, uppercase, lowercase etc. 3) Writing a function to count lowercase letters in a text file. 4) Writing a function to count words "Me" or "My" in a text file. 5) Removing lines containing "a" from a file and writing to a new file.

Uploaded by

Sakhyam Bhoi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
216 views20 pages

Xii SC Practical Assignment

The document contains instructions and source code for 9 programming assignments on working with files in Python. The assignments cover: 1) Reading a text file line by line and printing each word separated by #. 2) Reading a text file and counting vowels, consonants, uppercase, lowercase etc. 3) Writing a function to count lowercase letters in a text file. 4) Writing a function to count words "Me" or "My" in a text file. 5) Removing lines containing "a" from a file and writing to a new file.

Uploaded by

Sakhyam Bhoi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

VIKASH RESIDENTIAL SCHOOL, BARGARH

XII SC PRACTICAL ASSIGNMENTS


FOR THE AISSCE PRACTICAL EXAM-2022-23
COMPUTER SCIENCE (083)
(All the QUESTIONS/SOURCE CODES/OUTPUTS for practical record are prepared as per the syllabus
released by CBSE 2022-23 for partial fulfilment AISSCE practical exam-2022-23)
N: B-(Students have to maintain the comments in every programming codes)

1. Read a text file line by line and display each word separated by a #.
# SOURCE CODE
# Writing data into the text file
filein = open("Mydoc.txt",'w')
str=" "
n=int(input("enter the no of lines you want to write in a file"))
for k in range(n):
str =input("enter a line")
filein.write(str)
filein.write("\n")
filein.close()
# Reading data from file
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()
# OUTPUT
enter the no of lines you want to write in a file2
enter a lineQQQ WWW EEE RR TT
enter a lineXXX VVV FFF GGG HHH
QQQ#WWW#EEE#RR#TT
XXX#VVV#FFF#GGG#HHH
2. Read a text file and display the number of vowels/consonants/uppercase/lowercase
characters in the file.

# SOURCE CODE
filein = open("Mydoc1.txt",'w')
str=" "
n=int(input("enter the no of lines you want to write in a file"))
for k in range(n):
str =input("enter a line")
filein.write(str)
filein.write("\n")
filein.close()
filein = open("Mydoc1.txt",'r')
line = filein.read()
count_vow = 0
count_con = 0
count_low = 0
count_up = 0
count_digit = 0
count_other = 0
print(line)
for ch in line:
if ch.isupper():
count_up +=1
if ch.islower():
count_low += 1
if ch in 'aeiouAEIOU':
count_vow += 1
if ch.isalpha():
count_con += 1
if ch.isdigit():
count_digit += 1
if not ch.isalnum() and ch !=' ' and ch !='\n':
count_other += 1

print("Digits",count_digit)
print("Vowels: ",count_vow)
print("Consonants: ",count_con-count_vow)
print("Upper Case: ",count_up)
print("Lower Case: ",count_low)
print("other than letters and digit: ",count_other)
filein.close()
#OUTPUT
enter the no of lines you want to write in a file2
enter a lineINDIA is our Country
enter a lineWe feel proud for Our Country
INDIA is our Country
We feel proud for Our Country
Digits 0
Vowels: 18
Consonants: 23
Upper Case: 9
Lower Case: 32
other than letters and digit: 0

3. Write a function in python to count the number of lowercase alphabets present in a


text file.

# SOURCE CODE
filein = open("Mydoc3.txt",'w')
str=" "
n=int(input("enter the no of lines you want to write in a file"))
for k in range(n):
str =input("enter a line")
filein.write(str)
filein.write("\n")
filein.close()

filein = open("Mydoc3.txt",'r')
line = filein.read()
count_low = 0
for i in line:
if(i.islower()):
count_low=count_low+1
print("The number of lowercase characters is:")
print(count_low)
filein.close()
# OUTPUT
enter the no of lines you want to write in a file2
enter a lineRam is Very SMART
enter a lineHe used to Play With me
The number of lowercase characters is:
22.
4. Write a function in Python that counts the number of “Me” or “My” (in smaller case
also) words present in a text file.

# SOURCE CODE
def displayMeMy():
num=0
f=open("Mydoc4.txt","r")
N=f.read()
M=N.split()
for x in M:
if x=="Me" or x== "My":
print(x)
num=num+1
print("Count of Me/My in file:",num)
f.close()
filein = open("Mydoc4.txt",'w')
str=" "
n=int(input("enter the no of lines you want to write in a file"))
for k in range(n):
str =input("enter a line")
filein.write(str)
filein.write("\n")
filein.close()
displayMeMy()

# OUTPUT
enter the no of lines you want to write in a file2
enter a lineMe Mee My MMy Myy
enter a lineeMe Me Myy My YMy
Me
My
Me
My
Count of Me/My in file: 4
5. Remove all the lines that contain the character 'a' in a text file and write it to another
text file.

# SOURCE CODE
filein = open("Mydoc4.txt",'w')
str=" "
n=int(input("enter the no of lines you want to write in a file"))
for k in range(n):
str =input("enter a line")
filein.write(str)
filein.write("\n")
filein.close()
myfile = open("Mydoc4.txt", "r")
newfile = open("Mydoc6.txt", "w")
line = ""
while line:
line = myfile.readline()
if 'a' not in line:
print(line)
newfile.write(line)
myfile.close()
newfile.close()
print("Newly created file contains")
print("------------")
newfile = open("Mydoc6.txt","r")
line = ""
while line:
line = newfile.readline()
print(line)
newfile.close()
# OUTPUT
enter the no of lines you want to write in a file2
enter a lineindia is a country
enter a linei love my india
Newly created file contains
------------
i love my india
6. 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.

#SOURCE CODE
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(["Kanupriya", 4], f)
pickle.dump(["Aaheli", 5], f)
f.close()
#opeining 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")
#OUTPUT
Enter the Roll Number: 5
Name: Aaheli

7. Write a program to create a binary file to write 10 integers, read the file and display the
sum of even integers.

#SOURCE CODE
def accept_integer(file1):
import pickle
obj=open("file1","wb")
k=0
for k in range(10):
num=eval(input("enter an integer"))
pickle.dump(num,obj)

print("Data has been written into binary file")


print("---------------------------------------")

obj.close()

def read_integer(file1):
import pickle
obj=open("file1","rb")
val=0
try:
while True:
num=pickle.load(obj)
if num%2==0:
val+=num
except EOFError :
pass

print("Sum of all even numbers is",val)


print("------------------------------")

obj.close()

file1=input("Enter binary file name")


accept_integer(file1)
read_integer(file1)

#OUTPUT
Enter binary file namekk
enter an integer11
enter an integer23
enter an integer5
enter an integer4
enter an integer9
enter an integer7
enter an integer8
enter an integer12
enter an integer22
enter an integer13
Data has been written into binary file
---------------------------------------
Sum of all even numbers is 46

8. Write a program file to design binary file to store some numbers and search the
location of number whether it is present on that file or not after reading the file.

#SOURCE CODE
def accept_integer(file1):
import pickle
obj=open("file1","wb")
res='y'
while True:
num=eval(input("enter an integer"))
pickle.dump(num,obj)
res=input("do you want to cont.......[y/n]")
if res=="N" or res=="n":
break
print("Data has been written into binary file")
print("---------------------------------------")
obj.close()

def read_integer(file1):
import pickle
obj=open("file1","rb")
num1=eval(input("enter the number to search in file"))
loc=0
m=0
try:
while True:
num=pickle.load(obj)
m+=1
if num==num1:
print("number",num1,"found in",m,"position")
break

except EOFError :
pass
print("item not found from any position of the file")

obj.close()

file1=input("Enter binary file name")


accept_integer(file1)
read_integer(file1)

#OUTPUT
Enter binary file namepp
enter an integer1
do you want to cont.......[y/n]y
enter an integer4
do you want to cont.......[y/n]y
enter an integer6
do you want to cont.......[y/n]y
enter an integer8
do you want to cont.......[y/n]y
enter an integer7
do you want to cont.......[y/n]u
enter an integer3
do you want to cont.......[y/n]y
enter an integer2
do you want to cont.......[y/n]n
Data has been written into binary file
---------------------------------------
enter the number to search in file4
number 4 found in 2 position

9. Write a program to write some students information stored in a dictionary into a


binary file.Read that file and display all the information in the form of dictionary.
( Let each student information contain name, roll, age and mark).
#SOURCE CODE
def accept_dict1(file1):
import pickle
obj=open("file1","wb")
dict1=dict()
k=0
res='y'
while True:
name=input("enter student name")
roll=eval(input("enter students roll"))
age=eval(input("enter students age"))
mark=eval(input("enter students mark"))
b=(roll,age,mark)
dict1[name]=b
pickle.dump(dict1,obj)
res=input("do you want to cont.......[y/n]")
if res=="N" or res=="n":
break
print("Data has been written into binary file")
print("---------------------------------------")

obj.close()

def read_dict1(file1):
import pickle
obj=open("file1","rb")
try:
while True:
dict1=pickle.load(obj)
key=dict1.keys()
print(dict1)

except EOFError :
pass
print("Data has been displayed from binary file")
print("---------------------------------------")

obj.close()

file1=input("Enter binary file name")


accept_dict1(file1)
read_dict1(file1)

#OUTPUT
Enter binary file name student
enter student namealok
enter students roll33
enter students age19
enter students mark350
do you want to cont.......[y/n]y
enter student namedeepak
enter students roll34
enter students age18
enter students mark400
do you want to cont.......[y/n]n
Data has been written into binary file
---------------------------------------
{'alok': (33, 19, 350)}
{'alok': (33, 19, 350), 'deepak': (34, 18, 400)}
Data has been displayed from binary file
---------------------------------------

10. Write a Program in python to write a tuple of character strings and display the same
after reading it from the file.

#SOURCE CODE
# 1. The specified tuple with strings
T = ( 'abc', 'def', 'ghi', 'jk lmn')

f = open('myfile5.bin', 'wb')
for item in T:
bt = (item + '\n').encode() # convert (str + '\n') => bytes
f.write(bt) # write bt to file
f.close();

# 3. Read tuple from binary file 'myfile5.bin'


# 3.1. Open file for reading
f = open('myfile5.bin', 'rb')
# 3.2. A new tuple
T2 = ()
# 3.3. Read data from file
for line in f:
s = line.decode()
s = s[:-1]
T2 = T2 + (s,)

# 3.4. Print the tuple


print("T2 = ", T2)
# 3.5. Close file
f.close();

#OUTPUT
T2 = ('abc', 'def', 'ghi', 'jk lmn')

11. Write a program to add/insert records in file “data.csv”. Structure of a record is roll
number, name and class.

#SOURCE DORE

import csv

field = ["Roll no" , "Name" , "Class"]

f = open("data.csv" , 'w')

d=csv.writer(f)

d.writerow(field)

ch='y'

while ch=='y' or ch=='Y':

rn=int(input("Enter Roll number: "))

nm = input("Enter name: ")

cls = input("Enter Class: ")

rec=[rn,nm,cls]

d.writerow(rec)

ch=input("Enter more record??(Y/N)")

f.close()

#0UTPUT

Enter Roll number: 22


Enter name: ALOK
Enter Class: XI
Enter more record??(Y/N)Y
Enter Roll number: 33
Enter name: BIKASH
Enter Class: XII
Enter more record??(Y/N)N
12. Write a Program to create a CSV file Num1.csv, store a list of numbers in it and
display all number after reading it from file.

#SOURCE CODE

import csv
number=[100,200,300,400,500]
fin=open('num1.csv','w')
obj=csv.writer(fin)
obj.writerow(number)
fin.close()
fin=open('num1.csv','r')
obj=csv.reader(fin)
m=next(obj)
print(m)
fin.close()

#OUTPUT
List of numbers are
['100', '200', '300', '400', '500']

13. Write a program that depending upon user’s choice either push or pop an element in
a stack.

# SOURCE CODE

def Push_Stack(STACK,item):
STACK.append(item)
top=len(STACK)-1

def Stack_Pop(STACK):
if STACK==[]:
return "underflow"
else:
item=STACK.pop()
if len(STACK)==0:
top=None
else:
top=len(STACK)-1
return item

def Stack_Display(STACK):
if STACK==[]:
return "underflow"
else:
top=len(STACK)
#print(STACK[top]," ")
for a in range(0,top,1):
print(STACK[a])

STACK=[]
top=None
while True :
print("[1] Push")
print("[2] Pop")
print("[3] Dsiplay Stack")
print("[4] Exit")
ch=int(input("Enter your choice 1 to 4 "))
if ch==1:
item=input("Enter your item ")
Push_Stack(STACK,item)
elif ch==2:
item=Stack_Pop(STACK)
if item=="underflow":
print("Stack is empty")
else:
print("popped item is ",item)
elif ch==3:
Stack_Display(STACK)
else :
break

#OUTPUT

[1] Push
[2] Pop
[3] Dsiplay Stack
[4] Exit
Enter your choice 1 to 4 1
Enter your item 23
[1] Push
[2] Pop
[3] Dsiplay Stack
[4] Exit
Enter your choice 1 to 4 1
Enter your item 34
[1] Push
[2] Pop
[3] Dsiplay Stack
[4] Exit
Enter your choice 1 to 4 3
23
34
[1] Push
[2] Pop
[3] Dsiplay Stack
[4] Exit
14. Write a python program to implement PUSH(Books) and POP(Books) methods to add
books and Remove Books considering them to act as PUSH and POP operation of
STACK.

#SOURCE CODE

def Push_Book(BOOK,bname):
BOOK.append(bname)
top=len(BOOK)-1

def Pop_Book(BOOK):
if BOOK==[]:
return "underflow"
else:
bname=BOOK.pop()
if len(BOOK)==0:
top=None
else:
top=len(BOOK)-1
return bname

def Display_Book(BOOK):
if BOOK==[]:
return "underflow"
else:
top=len(BOOK)
for a in range(0,top,1):
print(BOOK[a])

BOOK=[]
top=None
while True :
print("[1] Push Book Name on Library")
print("[2] Pop Book Name from Library")
print("[3] Dsiplay Book Name")
print("[4] Exit")
ch=int(input("Enter your choice 1 to 4 "))
if ch==1:
bname=input("Enter your Book name ")
Push_Book(BOOK,bname)
elif ch==2:
bname=Pop_Book(BOOK)
if bname=="underflow":
print("Book Library is Empty")
else:
print("popped Book is ",bname)

elif ch==3:
Display_Book(BOOK)
else :
break

#OUTPUT

[1] Push Book Name on Library


[2] Pop Book Name from Library
[3] Dsiplay Book Name
[4] Exit
Enter your choice 1 to 4 1
Enter your Book name PYTHON
[1] Push Book Name on Library
[2] Pop Book Name from Library
[3] Dsiplay Book Name
[4] Exit
Enter your choice 1 to 4 3
PYTHON
[1] Push Book Name on Library
[2] Pop Book Name from Library
[3] Dsiplay Book Name
[4] Exit
Enter your choice 1 to 4

15. A line of text is read from the input terminal into a stack. Write an program to output
the String in the reverse order, each character appearing twice.
(e.g a b c d e should be changed to ee dd cc bb aa).

#SOURCE CODE

def Push_Char(LOC,cname):
LOC.append(cname)
top=len(LOC)-1

def Display_Char(LOC):
if LOC==[]:
return "underflow"
else:
top=len(LOC)
for a in range(top-1,-1,-1):
print(LOC[a]*2," ")

LOC=[]
top=None
while True:
print("[1] Enter the line of character one after another")
print("[2] Display the Character twice in reverse form")
print("[3] Exit")
ch=int(input("Enter your choice 1 to 4 "))
if ch==1:
a=int(input("Enter how many character you want to push in to the stack"))
while a!=0:
cname=input("Enter your character ")
Push_Char(LOC,cname)
a=a-1
elif ch==2:
Display_Char(LOC)
else:
break

#OUTPUT

[1] Enter the line of character one after another


[2] Display the Character twice in reverse form
[3] Exit
Enter your choice 1 to 4 1
Enter how many character you want to push in to the stack3
Enter your character E
Enter your character R
Enter your character T
[1] Enter the line of character one after another
[2] Display the Character twice in reverse form
[3] Exit
Enter your choice 1 to 4 2
TT
RR
EE
[1] Enter the line of character one after another
[2] Display the Character twice in reverse form
[3] Exit
Enter your choice 1 to 4

16. Consider the following tables FACULTY and COURSES. Write the MySQL queries
from (i) to (v).
FACULTY
F_ID Fname Lname Join_date Salary
102 Amit Mishra 12-10-1998 12000
103 Nitin Vyas 24-12-1994 8000
104 Rakshit Soni 18-5-2001 14000
105 Rashmi Malhotra 11-9-2004 11000
106 Sulekha Srivastava 5-6-2006 10000

COURSES
C_ID F_ID Cname Fees
C21 102 GridComputing 40000
C22 106 SystemDesign 16000
C23 104 ComputerSecurity 8000
C24 106 ComputerSecurity 15000
C25 102 SystemDesign 20000
C26 107 VisualBasic 6000

a. Increase the salary to 5% more of those FACULTY who have joined in between
2001 to 2006.
MySql> update FACULTY set Salary=Salary+(Salary*20/100) where year(Join_date)
in between 2001 and 2006;
b. display all the record of FACULTY in ascending order based on their Joining date.
MySql> select * from FACULTY order by Join_date;
c. Display CourseName and TotalFee of each similar courses .
MySql> select Cname, sum(Fees) ”TotalFee” from COURSES group by Cname;
d. Write the Sql query to add a new attribute LOCATION in a table TEACHER to store
the address of teachers.
MySql> alter table TEACHER add column (LOCATION char(15));
e. Write the Sql query remove course details from the table COURSES which is/are
not preferred by any teachers
MySql> delete from COURSE C, TEACHER T where C.F_ID<>T.F_ID;

17. Programs based on Python – SQL connectivity.


Consider the following tables STUDENT which is constructed under a database
STUDENTSDB in MySql.
Preview of the table STUDENT given below.

Write a Python program to do the proper connectivity with the database STUDENTDB
exist on MySql environment and write the query to update Fee 10% more of those
student whose names starts with “Su” and “Sh” and display.

CODES
import mysql.connector
db_connection = mysql.connector.connect(
host="localhost",
user="root",
passwd="root",
database="STUDENTDB"
)
db_cursor = db_connection.cursor()
ST=”UPDATE STUDENT SET price = price+(price*0.1) WHERE name LIKE "Su%" OR
"Sh%" “; #Updating records
db_cursor.execute(ST)
db_connection.close()
18. Consider the following tables TEACHER which is constructed under a database
SCHOOLDB in MySql.

Preview of the table TEACHER given below.

No. Name Department Date_of_ Joining Salary Sex


1. Raja Computer 21/5/1998 8000 M
2. Sangita History 21/5/1997 9000 F
3. Ritu Sociology 29/8/1998 8000 F
4. Kumar Linguistics 13/6/1996 10000 M
5. Venkatraman History 31/10/1999 8000 M
6. Sidhu Computer 21/5/1986 14000 M
7. Aishwarya Sociology 11/1/1988 12000 F

Write a Python program to do the proper connectivity with the database SCHOOLDB
exist on MySql environment and write the query to display the Name, Department, and
Salary of the lady teacher having maximum salary.
CODE
import mysql.connector
db_connection = mysql.connector.connect(
host="localhost",
user="root",
passwd="root",
database="SCHOOLDB"
)
db_cursor = db_connection.cursor()
ST=”SELECT Name, Department, MAX(Salary) FROM TEACHER WHERE
SEX="F" “; #Updating records
db_cursor.execute(ST)
db_connection.close()

19. Consider the following tables USER which is constructed under a database USER
DB in MySql.

Table USER
CID CName City ID
C1 Rohit Chennei 5
C2 Saket Mumbai 3
C3 Bhuvan Delhi 4
C4 Diksha Delhi 5
C5 Arjun Mumbai 1

Write a Python program to do the proper connectivity with the database USERDB exist
on MySql environment and write the query to display the information of those user
whose City is Delhi
CODE
import mysql.connector
db_connection = mysql.connector.connect(
host="localhost",
user="root",
passwd="root",
database="USERDB"
)
db_cursor = db_connection.cursor()
ST=”SELECT * FROM USER WHERE City=”Delhi” ; #Updating records
db_cursor.execute(ST)
data=db_cursor.fetchall()
for k in data:
print(k)
db_connection.close()

20. Consider the following tables ITEM which is constructed under a database ITEM_
DB in MySql.

Table ITEM
ID ItemName Manufacturer Price
1 Fridge A 10000
2 AC A 30000
3 Fridge X 12000
4 Fridge B 15000
5 AC C 32000

Write a Python program to do the proper connectivity with the database ITEM_DB exist
on MySql environment and write the query to INSERT a new recode into the table ITEM

CODE
import mysql.connector
db_connection = mysql.connector.connect(
host="localhost",
user="root",
passwd="root",
database="ITEM_DB"
)
db_cursor = db_connection.cursor()
db_cursor.execute(“INSERT into ITEM values ({ },’{ }’,’{ }’,{ })”.format(6,’AC’,’D’,31000))
db_connection.commit()
db_connection.close()

You might also like