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

XII CS Term1 Practical Solution

The document contains a computer science practical record for class 12 for term 1 of the academic year 2021-2022 from Kendriya Vidyalaya Ambarnath. It includes an index listing 18 assignments completed by the student, along with signatures from the examiner and principal. The assignments cover topics like searching and sorting lists in Python, working with files and CSVs, and menu-driven programs to perform string operations and calculate statistics from text files.

Uploaded by

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

XII CS Term1 Practical Solution

The document contains a computer science practical record for class 12 for term 1 of the academic year 2021-2022 from Kendriya Vidyalaya Ambarnath. It includes an index listing 18 assignments completed by the student, along with signatures from the examiner and principal. The assignments cover topics like searching and sorting lists in Python, working with files and CSVs, and menu-driven programs to perform string operations and calculate statistics from text files.

Uploaded by

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

KENDRIYA VIDYALAYA AMBARNATH, (SHIFT –I)

COMPUTER SCIENCE
PRACTICAL RECORD (TERM-
1)
CLASS : XII

2021-2022
Acknowledgement:
I, …………………………….of class XII –
Section ….. would like to express our sincere
gratitude to our
computer science teacher
Ms.APARNA DHIRDE,
PGT (COMPUTER SCIENCE), for her vital
support, guidance and encouragement –
without which
this project would not have come forth.

We would also like to express our gratitude to


our school KENDRIYA VIDYALAYA
AMBARNATH .

CERTIFICATE
This is to certify that, Practical on Computer Science
(Term-1) is successfully completed by
….……………………… of
Class: XII, Division: …….
Roll no. :………………..
for the academic year
2021-2022.
Signature:
Examiner (Subject Teacher)

Internal Examiner External Examiner

Principal

Date: / / 2022

INDEX
XII CS – Practical Assignments for TERM 1

S.No Description of Assignment Sign


1 Write a python program to search first occurrence of an element in
a list by using Linear search and display frequency of each element
present in list [List and search element should be entered by user]
2 Write a python program to sort elements of a list in ascending and
descending order by using bubble sort. Write user defined function.
3 Write a python program using function to pass list to a function
and double the odd values and half even values of a list and
display list element after changing.
4 Write a Python program input n numbers in tuple and count how
many even and odd numbers are entered.
5 Write a menu driven program in python to delete name of a
student from dictionary and to search phone no of a student by
student name. Create menu as below:
******MENU*******
1. Delete from Dictionary
2. Search Phone number using name from Dictionary
3. Exit
6 Write a menu driven program in python to do following
MENU
1. Reverse String
2. Check Whether string is Palindrome
3. Make half string in Uppercase
4. Exit
7 Write a program to read a list of n integers (positive as well as
negative). Create two new lists, one having all positive numbers
with sum and the other having all negative numbers with sum from
the given list.
8 Write a Python program to remove duplicates from a list.
9 Write a python code using function to search an element in a list
using Binary search method.
10 Write a menu driven program to generate random numbers given
in specific range and to display calendar after giving month and
year.
MENU
1. Generate Random numbers
2. Calender of a month
3.Exit
11 Write a python program to read and display file content line by line
with each word separated by #.
12 Write a python program Read a text file and display the number of
vowels/consonants/uppercase/lowercase alphabets in the file.
13 Write a python code that accepts a filename, and copies all lines
that do not start with a lowercase letter from the first file into the
second.
14 Write a python program to remove all the lines that contain the
character ‘a’ in a file and write it to another file.
15 Write a python program to create a binary file with name and roll
number. Search for a given roll number and display name, if not
found display appropriate message.
16 Write a python program to create a binary file with roll number,
name and marks. Input a roll number and update name and marks
17 Write a menu driven python program to create a CSV file by
entering dept-id, name and city, read and search the record for
given dept-id.
MENU
1. Create csv
2. Search
3.Exit
18 Write a Menu driven program in python to count spaces, digits,
words and lines from text file try.txt

XII CS – Practical Assignments for TERM 1

Assignment 1:

Write a python program to search first occurrence of an element in a list by using Linear search and
display frequency of each element present in list [List and search element should be entered by user]

Ans:
L=[]
c=0
n=int(input('how many items you want to enter in list:'))
for i in range(0,n):
a=int(input('enter item:'))
L.append(a)
print(L)
S=set(L)
S=list(S)
D={}
for i in S:

c=0
for j in L:
if i==j:
c+=1
D[i]=c
for k in D:
print("The frequency of ",k," is ", D[k])

ele=int(input("Enter item to be search:"))


flag=0
for i in range(0, n):
if (ele==L[i]):
flag=1
break
if (flag==1):
print("Element found at index",i,"and position",i+1)
else:
print("Element not found")

Output is:
how many items you want to enter in list:5
enter item:4
enter item:3
enter item:4
enter item:4
enter item:7
[4, 3, 4, 4, 7]
The frequency of 3 is 1
The frequency of 4 is 3
The frequency of 7 is 1
Enter item to be search:4
Element found at index 0 and position 1

Assignment 2:

Write a python program to sort elements of a list in ascending and descending order
by using bubble sort. Write user defined function.
Ans:
def BSort(Arr, S):

for i in range(S -1):


for j in range(S - i - 1):
if(Arr[j] > Arr[j + 1]):
temp = Arr[j]
Arr[j] = Arr[j + 1]
Arr[j + 1] = temp

Arr = [ ]
S = int(input("Please Enter the Total Number of Elements : "))
for i in range(S):
value = int(input("Please enter the %d Element of List1 : " %i))
Arr.append(value)

BSort(Arr, S)
print("The Sorted List in Ascending Order : ", Arr)
print("The Sorted List in Descending Order : ", Arr[::-1])

Output is:
Please Enter the Total Number of Elements : 5
Please enter the 0 Element of List1 : 34
Please enter the 1 Element of List1 : -8
Please enter the 2 Element of List1 : 544
Please enter the 3 Element of List1 : 3
Please enter the 4 Element of List1 : 2
The Sorted List in Ascending Order : [-8, 2, 3, 34, 544]
The Sorted List in Descending Order : [544, 34, 3, 2, -8]

Assignment 3:
Write a python program using function to pass list to a function and double the odd
values and half even values of a list and display list element after changing.

Ans:
def splitevenodd(A):
evenlist = []
oddlist = []
for i in A:
if (i % 2 == 0):
evenlist.append(i//2)
else:
oddlist.append(i*i)
print("Even lists:", evenlist)
print("Odd lists:", oddlist)
A=list()
n=int(input("Enter the size of the List ::"))
print("Enter the Elements of List ::")
for i in range(int(n)):
k=int(input(""))
A.append(k)
splitevenodd(A)

Output is:
Enter the size of List ::5
Enter the Elements of List ::
12
3
14
5
1
Even lists: [6, 7]
Odd lists: [9, 25, 1]

Assignment 4:
Write a Python program input n numbers in tuple and count how many even and odd
numbers are entered.
Ans:

l=[]

S = int(input("Please Enter the Total Number of Elements : "))


for i in range(S):
value = int(input("Please enter the %d Element of List1 : " %i))
l.append(value)
numbers=tuple(l)
count_odd = 0
count_even = 0
for x in numbers:
if not x % 2:
count_even+=1
else:
count_odd+=1
print("Number of even numbers :",count_even)
print("Number of odd numbers :",count_odd)

Output is:
Please Enter the Total Number of Elements : 5
Please enter the 0 Element of List1 : 34
Please enter the 1 Element of List1 : 3
Please enter the 2 Element of List1 : 2
Please enter the 3 Element of List1 : 56
Please enter the 4 Element of List1 : 3
Number of even numbers : 3
Number of odd numbers : 2

Assignment 5:
Write a menu driven program in python to delete name of a student from dictionary and to search
phone no of a student by student name. Create menu as below:
MENU
1. Delete from Dictionary
2. Search Phone number using name from Dictionary
3. Exit
Ans:

phonebook=dict()
while True:
print("******MENU\*******n")
print('1:Delete from Dictionary')
print('2:Search Phone number using name from Dictionary')
print('3:Exit\n')
ch=int(input('Enter your choice:'))
if ch==1:
n=int(input("Enter total number of friends:"))
i=1
while(i<=n):
a=input("enter name :")
b=int(input("enter phone number:"))
phonebook[a]=b
i=i+1
print(phonebook)
print('---------------------------------')
name=input("Enter name to delete:")
del phonebook[name]
k=phonebook.keys()
print("Phonebook Information")
print('---------------------')
print("Name",'\t',"Phone number")
for i in k:
print(i,'\t',phonebook[i])
if ch==2:
name=input("Enter name to search:")
f=0
k=phonebook.keys()
for i in k:
if(i==name):
print("Phone number= ",phonebook[i])
f=1
if (f==0):
print("Given name not exist")
if ch==3:
break
Output is:
******MENU\*******n
1:Delete from Dictionary
2:Search Phone number using name from Dictionary
3:Exit

Enter your choice:1


Enter total number of friends:2
enter name :APARNA
enter phone number:7083190774
{'APARNA': 7083190774}
---------------------------------
enter name :ARCHANA
enter phone number:9878390928
{'APARNA': 7083190774, 'ARCHANA': 9878390928}
---------------------------------
Enter name to delete:ARCHANA
Phonebook Information
---------------------
Name Phone number
APARNA 7083190774
******MENU\*******n
1:Delete from Dictionary
2:Search Phone number using name from Dictionary
3:Exit

Enter your choice:2


Enter name to search:APARNA
Phone number= 7083190774
******MENU\*******n
1:Delete from Dictionary
2:Search Phone number using name from Dictionary
3:Exit

Enter your choice:3

Assignment 6:
Write a menu driven program in python to do following
MENU
4. Reverse String
5. Check Whether string is Palindrome
6. Make half string in Uppercase
7. Exit
Ans:

while True:
print("******MENU*******\n")
print('1:Reverse String')
print('2:Check whether string is palindrome')
print('3:Make half string in Uppercase')
print('4:Exit\n')
ch=int(input('Enter your choice:'))
if ch==1:
st = input('Enter String:')
print(st[::-1])
if ch==2:
st = input('Enter String:')
if st==st[::-1]:
print('This string is palindrome')
else:
print('String is not palindrome')
if ch==3:
st = input('Enter String:')
print("The original string is : " + str(st))
# computing half index
hlf_idx = len(st) // 2
res = ''
for idx in range(len(st)):
# uppercasing later half
if idx >= hlf_idx:
res += st[idx].upper()
else :
res += st[idx]
# printing result
print("The resultant string : " + str(res))
if ch==4:
break

Output is:
******MENU*******
1:Reverse String
2:Check whether string is palindrome
3:Make half string in Uppercase
4:Exit

Enter your choice:1


Enter String:abc
cba
******MENU\*******n
1:Reverse String
2:Check whether string is palindrome
3:Make half string in Uppercase
4:Exit

Enter your choice:2


Enter String:madam
This string is palindrome
******MENU\*******n
1:Reverse String
2:Check whether string is palindrome
3:Make half string in Uppercase
4:Exit

Enter your choice:3


Enter String:aparna
The original string is : aparna
The resultant string : apaRNA
******MENU\*******n
1:Reverse String
2:Check whether string is palindrome
3:Make half string in Uppercase
4:Exit

Enter your choice:4


>>>

Assignment 7:
Write a program to read a list of n integers (positive as well as negative). Create two
new lists, one having all positive numbers with sum and the other having all negative
numbers with sum from the given list.
Ans:

list1=[]
plist1=[]
nlist1=[]
sum=0
sum1=0
n=int(input('how many elements u want in list:'))
for i in range(0,n):
a=int(input('enter item in list:'))
list1.append(a)
print('Original list is:',list1)
for i in range(0,n):
if list1[i]<0:
nlist1.append(list1[i])
sum=sum+list1[i]
else:
plist1.append(list1[i])
sum1=sum1+list1[i]
print('positive list is;',plist1)
print('sum of +ve numbers:',sum1)
print('Negative list is;',nlist1)
print('sum of -ve numbers:',sum)

Output is:
how many elements u want in list:4
enter item in list:3
enter item in list:2
enter item in list:-1
enter item in list:-1
Original list is: [3, 2, -1, -1]
positive list is; [3, 2]
sum of +ve numbers: 5
Negative list is; [-1, -1]
sum of -ve numbers: -2

Assignment 8:

Write a Python program to remove duplicates from a list.

Ans:
a=[]
n=int(input('how many elements u want in list:'))
for i in range(0,n):
n1=int(input('enter item in list:'))
a.append(n1)
print('Original list is:',a)
print('List after removing duplicate elements:')
dup_items = set()
uniq_items = []
for x in a:
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)
print(dup_items)

Output is:
how many elements u want in list:5
enter item in list:34
enter item in list:2
enter item in list:34
enter item in list:2
enter item in list:1
Original list is: [34, 2, 34, 2, 1]
List after removing duplicate elements:
{1, 34, 2}

Assignment 9:
Write a python code using function to search an element in a list using Binary search method.

Ans:
def binary_search(list1, n):
low = 0
high = len(list1) - 1
mid = 0

while low <= high:


# for get integer result
mid = (high + low) // 2

# Check if n is present at mid


if list1[mid] < n:
low = mid + 1
# If n is greater, compare to the right of mid
elif list1[mid] > n:
high = mid - 1

# If n is smaller, compared to the left of mid


else:
return mid

# element was not present in the list, return -1


return -1
# Initial list1
list1=[]
y=int(input('how many elements u want in list:'))
for i in range(0,y):
n1=int(input('enter item in ascending/descending order in list:'))
list1.append(n1)
x=(int(input('Enter item to search:')))

# Function call
result = binary_search(list1, x)

if result != -1:
print("Element is present at index", str(result),'and at position:',str(result+1))
else:
print("Element is not present in list1")

Output is:
how many elements u want in list:5
enter item in ascending/descending order in list:20
enter item in ascending/descending order in list:15
enter item in ascending/descending order in list:14
enter item in ascending/descending order in list:13
enter item in ascending/descending order in list:12
Enter item to search:14
Element is present at index 2 and at position: 3
Assignment 10:
Write a menu driven program to generate random numbers given in specific range
and to display calendar after giving month and year.

MENU
1. Generate Random numbers
2. Calender of a month
3.Exit
Ans:
# Program to display calendar of the given month and year

import random
import calendar
while True:
print("******MENU*******\n")
print('1:Random Number generators')
print('2:Calender of a month')
print('3:Exit\n')
ch=int(input('Enter your choice:'))
if ch==1:
num = 10
start = 20
end = 40
res = []
for j in range(num):
res.append(random.randint(start, end))
print(res)
if ch==2:
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))
print(calendar.month(yy, mm))
if ch==3:
break

Output is:
******MENU*******

1:Random Number generators


2:Calender of a month
3:Exit

Enter your choice:1


[39, 21, 21, 29, 22, 36, 33, 32, 20, 31]
******MENU*******

1:Random Number generators


2:Calender of a month
3:Exit

Enter your choice:2


Enter year: 2021
Enter month: 7
July 2021
Mo Tu We Th Fr Sa Su
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

******MENU*******

1:Random Number generators


2:Calender of a month
3:Exit

Enter your choice:3


>>>

Assignment 11:
Write a python program to read and display file content line by line with each word
separated by #.

Ans:
file=input('Enter the file: ')
f =open( file,'r')
item=[]
for line in f:
words=line.split()
for i in words:
item.append(i)
print('#'.join(item))

Output is:
Enter the file: i.txt
i#like#india
Assignment 12:
Write a python program Read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file.
Ans:
def cnt():
f=open('i.txt','r')
cont=f.read()

v=0
c=0
lcl=0
ucl=0
for ch in cont:
if(ch.islower()):
lcl=lcl+1
elif (ch.isupper()):
ucl=ucl+1
if (ch in['a','e','i','o','u'] or ch in['A','E','I','O','U']):
v=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'] or ch in['B', 'C',
'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W','X', 'Y','Z']):
c=c+1
f.close()
print('Vowels are:',v)
print('Consonents are:',c)
print('Lowercase letters are:',lcl)
print('Uppercase letters are:',ucl)

cnt()

Output is:
Vowels are: 6
Consonents are: 4
Lowercase letters are: 10
Uppercase letters are: 0

Assignment 13:
Write a python code that accepts a filename, and copies all lines that do not start with
a lowercase letter from the first file into the second.

Ans:

fin =open ('oldfile.txt','r')


fout= open ('newfile.txt', 'w')
text =fin.readlines()
for line in text:
if line[0].isalpha():
if not line[0] in 'abcdefghijklmnopqrstuvwxyz':
fout.write(line)
fin.close()
fout.close()

Output is:
Assignment 14:
Write a python program to remove all the lines that contain the character ‘a’ in a file
and write it to another file.
Ans:

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()
Output is:

Assignment 15:
Write a python program to create a binary file with name and roll number. Search for
a given roll number and display name, if not found display appropriate message.
Ans:
import pickle
while True:
rollno = int(input('Enter roll number:'))
name = input('Enter Name:')

#Creating the dictionary


rec = {'Rollno':rollno,'Name':name}
#Writing the Dictionary
f = open('student.dat','ab')
pickle.dump(rec,f)
ch=input('Wish to enter more record (Y/N):')
if ch=='N' or ch=='n':
break
f.close()
f = open('student.dat','rb')
flag = False
r=int(input('Enter rollno to be searched='))
while True:
try:
rec = pickle.load(f)
if rec['Rollno'] == r:
print('Roll Num:',rec['Rollno'])
print('Name:',rec['Name'])

flag = True
except EOFError:
break
if flag == False:
print('No Records found')
f.close()

Output is:
Enter roll number:1
Enter Name:APARNA DHIRDE
Wish to enter more record (Y/N):Y
Enter roll number:2
Enter Name:MANGESH
Wish to enter more record (Y/N):Y
Enter roll number:3
Enter Name:VEERA
Wish to enter more record (Y/N):N
Enter rollno to be searched=2
Roll Num: 2
Name: MANGESH
Assignment 16:
Write a python program to create a binary file with roll number, name and marks.
Input a roll number and update name and marks
Ans:
import pickle
while True:
rollno = int(input('Enter roll number:'))
name = input('Enter Name:')
marks = int(input('Enter Marks:'))
#Creating the dictionary
rec = {'Rollno':rollno,'Name':name,'Marks':marks}
#Writing the Dictionary
f = open('student1.dat','ab')
pickle.dump(rec,f)
ch=input('Wish to enter more record (Y/N):')
if ch=='N' or ch=='n':
break
f.close()
f=open('student1.dat','rb+')
found=0

r=int(input('Enter roll no to search :'))


while True:
rec=pickle.load(f)
if rec['Rollno']==r:
print('Current name is:',rec['Name'])
print('Current Marks are:',rec['Marks'])
rec['Name']=input('Enter new name:')
rec['Marks']=int(input('Enter new marks:'))
found=1
break
if found==1:
f.seek(0)
pickle.dump(rec,f)
print('Record updated')

f.close()

Output is:
Enter roll number:1
Enter Name:ASHWINI UPARE
Enter Marks:456
Wish to enter more record (Y/N):Y
Enter roll number:2
Enter Name:MANOJ PATIL
Enter Marks:400
Wish to enter more record (Y/N):N
Enter roll no to search :2
Current name is: MANOJ PATIL
Current Marks are: 400
Enter new name:MANOJ ASHOK PATIL
Enter new marks:500
Record updated
Assignment 17:
Write a menu driven python program to create a CSV file by entering dept-id, name
and city, read and search the record for given dept-id.
MENU
1. Create csv
2. Search record as per dept no
3.Exit
Ans:
import csv
while True:
print('*** MENU ***\n')
print('1: create csv file')
print('2: Search as per id')
print('3: Exit')
ch=int(input('Enter choice:'))
if ch==1:
f=open('dept.csv','a')
mywriter=csv.writer(f,delimiter=',')
ans='y'
while ans.lower()=='y':
rno=int(input('Enter dept no:'))
name=input('Enter dept name:')
clas=input('Enter city:')
mywriter.writerow([rno,name,clas])
print('## Data Saved ##')
ans=input('Add More?:')
f.close()
if ch==2:
print("Search a Record")
print("===================")
f=open('dept.csv','r',newline='\r\n') #Remove new line character from output
r=input('Enter DEPT no you want to search:')
s=csv.reader(f)
for rec in s:
if rec[0]==r:
print("Rollno=",rec[0])
print("Name=",rec[1])
print("Marks=",rec[2])
f.close()
if ch==3:
break
Output is:
*** MENU ***

1: create csv file


2: Search as per id
3: Exit
Enter choice:1
Enter dept no:10
Enter dept name:MATH
Enter city:PUNE
## Data Saved ##
Add More?:y
Enter dept no:20
Enter dept name:HINDI
Enter city:PUNE
## Data Saved ##
Add More?:n
*** MENU ***

1: create csv file


2: Search as per id
3: Exit
Enter choice:2
Search a Record
===================
Enter DEPT no you want to search: 20
Rollno= 20
Name= HINDI
Marks= PUNE
*** MENU ***

1: create csv file


2: Search as per id
3: Exit
Enter choice:3
>>>

Assignment 18:
Write a Menu driven program in python to count spaces, digits, words and lines from
text file try.txt

Ans:

while True:
print('*** MENU ***\n')
print('1: count spaces')
print('2: count digits')
print('3: count words')
print('4: count lines')
print('5: exit')
ch=int(input('enter your choice:'))
if ch==1:
F1=open('abc.txt', 'r')
c=0
F=F1.read()
for letter in F:
if( letter.isspace( )):
c=c+1
print('No. of spaces are:',c)
F1.close()
if ch==2:
c=0
F1=open('abc.txt', 'r')
F=F1.read()
for letter in F:
if( letter.isdigit( )):
c=c+1

print('No. of digits are:',c)

F1.close()
if ch==3:
f=open("abc.txt","r")
linesList=f.readlines()
count=0
for line in linesList:
wordsList=line.split()
print(wordsList)
count = count+ len(wordsList)
print("The number of words in this file are : ",count)
f.close()
if ch==4:
count =0
f=open("abc.txt","r")
data=f.readlines()
print(data)
for line in data:
count=count+1
print("Number of lines : " ,count)
f.close()
if ch==5:
break

Output is:
*** MENU ***

1: count spaces
2: count digits
3: count words
4: count lines
5: exit
enter your choice:1
No. of spaces are: 8
*** MENU ***
1: count spaces
2: count digits
3: count words
4: count lines
5: exit
enter your choice:2
No. of digits are: 4
*** MENU ***

1: count spaces
2: count digits
3: count words
4: count lines
5: exit
enter your choice:3
['Sky', 'is', 'blue', '2021.']
['i', 'like', 'rainy', 'season.']
The number of words in this file are : 8
*** MENU ***

1: count spaces
2: count digits
3: count words
4: count lines
5: exit
enter your choice:4
['Sky is blue 2021.\n', 'i like rainy season.\n']
Number of lines : 2
*** MENU ***

1: count spaces
2: count digits
3: count words
4: count lines
5: exit
enter your choice:5
>>>

You might also like