0% found this document useful (0 votes)
96 views6 pages

12 CS Practical Solved

Uploaded by

suryanshslnk
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)
96 views6 pages

12 CS Practical Solved

Uploaded by

suryanshslnk
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

SET 1

1. Write a function in Python that counts the number of “Me” or “My” words present
in a text file “STORY.TXT”.
def displayMeMy():
num=0
f=open("story.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()

displayMeMy()

2. Write a function in python that displays the number of lines starting with ‘H’ in
the file “para.txt”.
def countH():
f=open("para.txt","r")
lines=0 l=f.readlines()
for i in l:
if i[0]='H':
lines+=1
print("NO of lines are:",lines)
f.close()
3. Write a function VowelCount() in Python, which should read each character of a text file
MY_TEXT_FILE.TXT, should count and display the occurrence of alphabets vowels.
4. Write a function that counts and display the number of 5 letter words in a text file
“Sample.txt”.

5. Create a CSV file by entering user-id and password, read and search the password for
given userid.
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)

# print(i,given)
if i[0] == given:
print(i[1])
break
output

enter id: cbse


enter password: 123
press Y/y to continue and N/n to terminate the program
y
enter id: computer_sc
enter password: python
press Y/y to continue and N/n to terminate the program
y
enter id: cs083
enter password: class12
press Y/y to continue and N/n to terminate the program
n
enter the user id to be searched
cbse
123
6. Create a binary file with the name and roll number.
Search for a given roll number and display the name, if
not found display appropriate message.
#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.
# 1. Inserting/Appending
# 2. Reading/Display
# 3. Searching

import pickle

def Writerecord(sroll,sname):
with open ('StudentRecord1.dat','ab') as Myfile:
srecord={"SROLL":sroll,"SNAME":sname}
pickle.dump(srecord,Myfile)

def Readrecord():
with open ('StudentRecord1.dat','rb') as Myfile:
print("\n-------DISPALY STUDENTS DETAILS--------")
print("\nRoll No.",' ','Name','\t',end='')
print()
while True:
try:
rec=pickle.load(Myfile)
print(' ',rec['SROLL'],'\t ' ,rec['SNAME'])
except EOFError:
break
def Input():
n=int(input("How many records you want to create :"))
for ctr in range(n):
sroll=int(input("Enter Roll No: "))
sname=input("Enter Name: ")
Writerecord(sroll,sname)

def SearchRecord(roll):
with open ('StudentRecord1.dat','rb') as Myfile:
while True:
try:
rec=pickle.load(Myfile)
if rec['SROLL']==roll:
print("Roll NO:",rec['SROLL'])
print("Name:",rec['SNAME'])

except EOFError:
print("Record not find..............")
print("Try Again..............")
break

def main():

while True:
print('\nYour Choices are: ')
print('1.Insert Records')
print('2.Dispaly Records')
print('3.Search Records (By Roll No)')
print('0.Exit (Enter 0 to exit)')
ch=int(input('Enter Your Choice: '))
if ch==1:
Input()
elif ch==2:
Readrecord()
elif ch==3:
r=int(input("Enter a Rollno to be Search: "))
SearchRecord(r)
else:
break
main()

8. Write a program to perform read and write operation


onto a student.csv file having fields as roll number,
name, stream and percentage.
# Write user-defined functions to perform read and write
# operation onto a student.csv file having fields
# as roll number, name, stream and percentage.

import csv
with open('Student_Details.csv','w',newline='') as csvf:
writecsv=csv.writer(csvf,delimiter=',')
choice='y'
while choice.lower()=='y':
rl=int(input("Enter Roll No.: "))
n=input("Enter Name: ")
p=float(input("Enter Percentage: "))
r=input("Enter Remarks: ")
writecsv.writerow([rl,n,p,r])
print(" Data saved in Student Details file..")
choice=input("Want add more record(y/n).....")

with open('Student_Details.csv','r',newline='') as fileobject:


readcsv=csv.reader(fileobject)
for i in readcsv:
print(i)
9. Write a random number generator that generates random
numbers between 1 and 6 (simulates a dice).
#Write a random number generator that generates random numbers
#between 1 and 6 (simulates a dice).

import random
import random

def roll_dice():
print (random.randint(1, 6))
print("""Welcome to my python random dice program!
To start press enter! Whenever you are over, type quit.""")

flag = True
while flag:
user_prompt = input(">")
if user_prompt.lower() == "quit":
flag = False
else:
print("Rolling dice...\nYour number is:")
roll_dice()
10. Write a python program to implement a stack using
a list data-structure.
# Write a python program to implement a stack using a list data-structure.
#IMPLIMENTATION OF STACK

def isempty(stk):
if stk==[]:
return True
else:
return False

def push(stk,item):
stk.append(item)
top=len(stk)-1

def pop(stk):
if isempty(stk):
return "underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item

def peek(stk):
if isempty(stk):
return "underflow"
else:
top=len(stk)-1
return stk[top]

def display(stk):
if isempty(stk):
print('stack is empty')
else:
top=len(stk)-1
print(stk[top],'<-top')
for i in range(top-1,-1,-1):
print(stk[i])

#Driver Code

def main():
stk=[]
top=None
while True:
print('''stack operation
1.push
2.pop
3.peek
4.display
5.exit''')
choice=int (input('enter choice:'))
if choice==1:
item=int(input('enter item:'))
push(stk,item)
elif choice==2:
item=pop(stk)
if item=="underflow":
print('stack is underflow')
else:
print('poped')
elif choice==3:
item=peek(stk)
if item=="underflow":
print('stack is underflow')
else:
print('top most item is:',item)
elif choice==4:
display(stk)
elif choice==5:
break
else:
print('invalid')
exit()
main()

Q. Write a python program that reads a text file New.txt, line by line and display
each word separated by a #.
Q. Write a program in python to count the number of lines in a text file ‘Country.txt’
which are starting with an alphabet ‘W’ or ‘H’.

You might also like