0% found this document useful (0 votes)
87 views15 pages

12 CS Practical-1

The document contains 11 questions about computer science practical topics like file handling, stacks, CSV files, and random number generation in Python. For each question, it provides the aim, source code, and output to write a program to accomplish the given task, such as reading and processing text files, creating and searching binary and CSV files, and generating random numbers. The programs are all executed successfully as shown in the output sections.

Uploaded by

Sandeep Moury
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)
87 views15 pages

12 CS Practical-1

The document contains 11 questions about computer science practical topics like file handling, stacks, CSV files, and random number generation in Python. For each question, it provides the aim, source code, and output to write a program to accomplish the given task, such as reading and processing text files, creating and searching binary and CSV files, and generating random numbers. The programs are all executed successfully as shown in the output sections.

Uploaded by

Sandeep Moury
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/ 15

Grade 12: COMPUTER SCIENCE

PRACTICAL FILE (2022-2023)


Part – I (Python file handling, stacks, csv)
1. Question:
Write a python program to read a text file line by line and display each word separated by a #.
Aim:
To write a python program to read a text file line by line and display each word separated by a #.
Source code:
a=open(r"C:\Users\HP\Desktop\Hello World.txt","r")
lines=a.readlines()
for line in lines:
x=line.split()
for y in x:
print(y+" # ",end=" ")
print(" ")
Output:

Result:
The above program is executed successfully and the output is shown.

2. Question:
Write a Python program to read a text file and display the number of vowels/ consonants/ uppercase/ lowercase
characters in the file.
Aim:
Write a Python program to read a text file and display the number of vowels/ consonants/ uppercase/ lowercase
characters in the file.
Source Code:
def cnt():
f=open(r"C:\Users\HP\Desktop\2.txt","r")
cont=f.read()
print(cnt)
v=0
cons=0
lc=0
uc=0
for ch in cont:
if (ch.islower()):
lc+=1
elif(ch.isupper()):
uc+=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 : ",lc)
print("Upper case letters are : ",uc)
cnt()
Output:

Result:
The above program is executed successfully and the output is shown.

3. Question:
Write a python program to remove all the lines that contain the character `a’ in a file and write it to another file.
Aim:
To write a python program to remove all the lines that contain the character `a’ in a file and write it to another file.
Source Code:
file=open(r"C:\Users\HP\Desktop\book.txt","r")
lines=file.readlines()
file.close()
file=open(r"C:\Users\HP\Desktop\book.txt","w")
file1=open(r"C:\Users\HP\Desktop\copy.txt","w")
for line in lines:
if 'a' in line:
file1.write(line)
else:
file.write(line)
print("Lines that contain a character are removed from book")
print("Lines that contain a character are added in copy")
file.close()
file1.close()
Output:

Result:
The above program is executed successfully and the output is shown.

4. Question:
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 write a python program 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.
Source Code:
import pickle
sdata={}
slist=[]
totals=int(input("Enter no.of students:"))
for i in range(totals):
sdata["Roll no."]=int(input("enter roll no.:"))
sdata["Name"]=input("Enter name:")
slist.append(sdata)
sdata={}
a=open(r"C:\Users\HP\Desktop\text.dat","wb")
pickle.dump(slist,a)
a.close()
x=open(r"C:\Users\HP\Desktop\text.dat","rb")
slist=pickle.load(x)
b=int(input("Enter the roll number of student to be searched:"))
y=False
for text in slist:
if(text["Roll no."]==b):
y=True
print(text["Name"],"Found in file")
if(y==False):
print("Data of student not found")
Output:

Result:
The above program is executed successfully and the output is shown.
5. Question:
Write a Python Program to Create a binary file with Empno, Name, Salary, then read and display their details on screen
Aim:
To Write a Python Program to Create a binary file with Empno, Name, Salary, then read and display their details on screen
Source Code:
import pickle
def Write():
F=open("Emp.dat",'ab')
D={}
n=int(input("Enter how many employee details you want to store:"))
for i in range(n):
D['emp no']=int(input("Enter the employee number:"))
D['emp name']=input("Enter the employee name:")
D['Salary']=int(input("Enter the employee salary:"))
pickle.dump(D,F)
F.close()

def Read():
F=open("Emp.dat",'rb')
try:
while True:
s=pickle.load(F)
print(s)
except:
F.close()
Write()
Read()
Output:
Result:
The above program is executed successfully and the output is shown.

6. Question:
Take a sample text file and find the most commonly occurring word. Also, list the frequencies of words in the text file.
Aim:
To take a sample text file and find the most commonly occurring word. Also, list the frequencies of words in the text file.
Source Code:
with open(r"C:\Users\HP\Desktop\text1.txt",'r') as fh:
contents=fh.read()
wordlist=contents.split()
wordfreq=[]
high=0
word=''
existing=[]
for w in wordlist:
wcount=wordlist.count(w)
if w not in existing:
wordfreq.append([w,wcount])
existing.append(w)
if wcount>high:
high=wcount
word=w
print("The word'"+word+"' occurs maximum number of times,",high,"times.")
print("\n other words have these frequencies:")
print(wordfreq)
Output:

Result:
The above program is executed successfully and the output is shown.

7. Question:
Create a binary file with roll number, name and marks. Input a roll number and update the marks.
Aim:
To write a python program to create a binary file with roll number, name and marks. Input a roll number and update the
marks.
Source code:
import pickle
sdata={}
totals=int(input("Enter the no.of students"))
a=open(r"C:\Users\HP\Desktop\text1.dat","wb")
for i in range(totals):
sdata["Roll no"]=int(input("Enter roll no:"))
sdata["Name"]=input("Enter name:")
sdata["Marks"]=float(input("Enter marks:"))
pickle.dump(sdata,a)
sdata={}
a.close()
found=False
rollno=int(input("Enter roll no to update:"))
a=open(r"C:\Users\HP\Desktop\text1.dat","rb+")
try:
while True:
pos=a.tell()
sdata=pickle.load(a)
if(sdata["Roll no"]==rollno):
sdata["Marks"]=float(input("Enter new marks:"))
a.seek(pos)
pickle.dump(sdata,a)
found=True
except EOFError:
if found==False:
print("Roll number not found")
else:
print("Student marks updated successfully")
a.close()
Output:

Result:
The above program is executed successfully and the output is shown.

8. Question:
Write a python program to create a random number generator that generates random numbers between 1 and 6
(simulates a dice).
Aim:
To create a random number generator that generates random numbers between 1 and 6 (simulates a dice).
Source Code:
import random
import time
print("Press CTRL+C to stop the dice ")
play='y'
while play=='y':
try:
while True:
for i in range(10):
print()
n = random.randint(1,6)
print(n,end='')
time.sleep(.00001)
except KeyboardInterrupt:
print("Your Number is :",n)
ans=input("Play More? (Y) :")
if ans.lower()!='y':
play='n'
break
Output:

Result:
The above program is executed successfully and the output is shown.

9. Question:
Program to take 10 sample phishing email, and find the most common word occurring
Aim:
To write a program to take 10 sample phishing email, and find the most common word occurring
Source code:
phishingemail=[
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
"[email protected]"
"[email protected]"
"[email protected]"
"[email protected]"
]
myd={}
for e in phishingemail:
x=e.split('@')
for w in x:
if w not in myd:
myd[w]=1
else:
myd[w]+=1
key_max = max(myd,key=myd.get)
print("Most Common Occuring word is :",key_max)
Output:

Result:
The above program is executed successfully and the output is shown.

10. Question:
Create a CSV file by entering user-id and password, read and search the password for given user- id.
Aim:
To write a program to create a CSV file by entering user-id and password, read and search the password for given user- id.
Source Code:
import csv
with open("7.csv", "w") as obj:
fileobj = csv.writer(obj)
fileobj.writerow(["User Id", "password"])
while(True):
user_id = input("enter id: ")
password = input("enter password: ")
record = [user_id, password]
fileobj.writerow(record)
x = input("press Y/y to continue and N/n to terminate the program\n")
if x in "Nn":
break
elif x in "Yy":
continue
with open("7.csv", "r") as obj2:
fileobj2 = csv.reader(obj2)
given = input("enter the user id to be searched\n")

for i in fileobj2:
next(fileobj2)

if i[0] == given:
print(i[1])
break
Output:

Result:
The above program is executed successfully and the output is shown.

11. Question:
Create a python program to create and search students’ record in CSV file.
Aim:
To write a Python program Create a CSV file to store Rollno, Name, Age and search any Rollno and display Name, Age and
if not found display appropriate message.
Source Code:
import csv
def Create():
F=open("Stu.csv",'a')
W=csv.writer(F)
opt='y'
while opt=='y':
No=int(input("Enter the student roll number:"))
Name=input("Enter the student name:")
Age=int(input("Enter the student age:"))
L=[No,Name,Age]
W.writerow(L)
opt=input("Do you want to add another student detail?(y/n):")
F.close()
def Read():
F=open("Stu.csv",'r',newline='\r\n')
no=int(input("Enter student roll number to search:"))
found=0
row=csv.reader(F)
for data in row:
if data[0]==str(no):
print("Student details are:")
print("=============================")
print("Name:",data[1])
print("Age:",data[2])
print("=============================")
found=1
break
if found==0:
print("The student roll number is not found")
F.close()
Create()
Read()

Output:

Result:
The above program is executed successfully and the output is shown.

12. Question:
Write a program to create a CSV file with empid, name and mobile no. and search empid, update the record and
display the records.
Aim:
To Write a program to create a CSV file with empid, name and mobile no. and search empid, update the record and
display the records.
Source code:
import csv
with open(r'C:\Users\HP\Desktop\employee.txt','a') as csvfile:
mywriter=csv.writer(csvfile,delimiter=',')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter employee ID:"))
name=input("Enter employee name:")
mobno=int(input("Enter employee mobile no:"))
mywriter.writerow([eno,name,mobno])
ans=input("Do you want to enter more data? (y/n):")
ans='y'

with open(r'C:\Users\HP\Desktop\employee.txt','r') as csvfile:


myreader=csv.reader(csvfile,delimiter=',')
ans='y'
while ans.lower()=='y':
found=False
e=int(input("Enter employee ID to search:"))
for row in myreader:
if len(row)!=0:
if int(row[0])==e:
print("Name:",row[1])
print("Mobile No.:",row[2])
found=True
break
if not found:
print("Employee ID not found")
ans=input("Do you want to search more? (y/n):")
ans='y'

with open(r'C:\Users\HP\Desktop\employee.txt','a') as csvfile:


x=csv.writer(csvfile)
x.writerow([eno,name,mobno])
Output:

Result:
The above program is executed successfully and the output is shown.

13. Question:
Write a Python program to implement a stack using list (PUSH & POP Operation on Stack).
Aim:
To write a Python program to implement a stack using list (PUSH & POP Operation on Stack).
Source code:
def isEmpty(s):
if len(s)==0:
return True
else:
return False
def push(s,item):
s.append(item)
top=len(s)-1
def pop(s):
if isEmpty(s):
return 'Underflow occurs'
else:
val=s.pop()
if len(s)==0:
top=None
else:
top=len(s)-1
return val
def peek(s):
if isEmpty(s):
return 'Underflow occurs'
else:
top=len(s)-1
return s[top]
def show(s):
if isEmpty(s):
print('no item found')
else:
t=len(s)-1
print('(TOP)',end='')
while(t>=0):
print(s[t],'<==',end='')
t=t-1
print()
s=[]
top=None
while True:
print('****** STACK IMPLEMENTATION USING LIST ******')
print('1: PUSH')
print('2: POP')
print('3: PEEK')
print('4: Show')
print('0: Exit')
ch=int(input('Enter choice:'))
if ch==1:
val=int(input('Enter no to push:'))
push(s,val)
elif ch==2:
val=pop(s)
if val=='Underflow':
print('Stack is empty')
else:
print('\nDeleted item is:',val)
elif ch==3:
val=peek(s)
if val=='Underflow':
print('Stack is empty')
else:
print('\nTop item is:',val)
elif ch==4:
show(s)
elif ch==0:
print('Bye')
break
Output:

Result:
The above program is executed successfully and the output is shown.

14. Question:
Write a python program using function PUSH(Arr), where Arr is a list of numbers. From this list push all numbers divisible
by 5 into a stack implemented by using a list. Display the stack if it has at least one element, otherwise display
appropriate error message.
Aim:
To write a python program using function PUSH(Arr), using a list of numbers, push all numbers divisible by 5 into the
stack and display the stack if it has at least one element, otherwise display appropriate error message.

Source Code:
def isEmpty(Arr):
if len(Arr)==0:
return True
else:
return False
def push(Arr,item):
if item%5==0:
Arr.append(item)
top=len(Arr)-1
def show(Arr):
if isEmpty(Arr):
print('No item found')
else:
t=len(Arr)-1
print('(TOP)',end='')
while(t>=0):
print(Arr[t],'<==',end='')
t=t-1
print()
Arr=[]
top=None
while True:
print('****** STACK IMPLEMENTATION USING LIST ******')
print('1: PUSH')
print('2: Show')
print('0: Exit')
ch=int(input('Enter choice:'))
if ch==1:
val=int(input('Enter no to push:'))
push(Arr,val)
elif ch==2:
show(Arr)
elif ch==0:
print('Bye')
break
Output:
Result:
The above program is executed successfully and the output is shown.

15. Question:
Write a python program using function POP(Arr), where Arr is a stack implemented by a list of numbers and the function
should return the value deleted from the stack.
Aim:
To write a python program using function POP(Arr), where Arr is a stack implemented by a list of numbers and a function
that returns the value deleted from the stack.
Source code:
def isEmpty(Arr):
if len(Arr)==0:
return True
else:
return False
def push(Arr,item):
Arr.append(item)
top=len(Arr)-1
def pop(Arr):
if isEmpty(Arr):
return 'Underflow occurs'
else:
val=Arr.pop()
if len(Arr)==0:
top=None
else:
top=len(Arr)-1
return val
def show(Arr):
if isEmpty(Arr):
print('no item found')
else:
t=len(Arr)-1
print('(TOP)',end='')
while(t>=0):
print(Arr[t],'<==',end='')
t=t-1
print()
Arr=[]
top=None
while True:
print('****** STACK IMPLEMENTATION USING LIST ******')
print('1: PUSH')
print('2: POP')
print('3: Show')
print('0: Exit')
ch=int(input('Enter choice:'))
if ch==1:
val=int(input('Enter no to push:'))
push(Arr,val)
elif ch==2:
val=pop(Arr)
if val=='Underflow':
print('Stack is empty')
else:
print('\nDeleted item is:',val)
elif ch==3:
show(Arr)
elif ch==0:
print('Bye')
break
Output:

Result:
The above program is executed successfully and the output is shown.

You might also like