CS - Lab Practical
CS - Lab Practical
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()
2. Read a text file and display the number of vowels/ consonants/ uppercase/ lowercase
characters and other than character and digit in the file.
filein = open("MyDoc.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()
3. Remove all the lines that contain the character `a' in a file and write it to another file
f1 = open("Mydoc.txt")
f2 = open("copyMydoc.txt","w")
for line in f1:
if 'a' not in line:
f2.write(line)
print('## File Copied Successfully! ##')
f1.close()
f2.close()
f2 = open("copyMydoc.txt","r")
print(f2.read())
4. 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.
import pickle
def Writerecord():
with open (‘StudentRecord1.dat','ab') as Myfile:
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: ")
srecord={"SROLL":sroll,"SNAME":sname}
pickle.dump(srecord,Myfile)
def SearchRecord():
with open ('StudentRecord1.dat','rb') as Myfile:
while True:
try:
rec=pickle.load(Myfile)
roll=int(input("Enter a Rollno to be Search: "))
if rec['SROLL']==roll:
print("Roll NO:",rec['SROLL'])
print("Name:",rec['SNAME'])
except EOFError:
print("Record not find..............")
print("Try Again..............")
break
Writerecord()
SearchRecord()
5. Create a binary file with roll number, name and marks. Input a roll number and update the
marks.
import pickle
def Writerecord():
with open ('StudentRecord.dat','ab') as Myfile:
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: ")
sperc=float(input("Enter Percentage: "))
sremark=input("Enter Remark: ")
srecord={"SROLL":sroll,"SNAME":sname,"SPERC":sperc,
"SREMARKS":sremark}
pickle.dump(srecord,Myfile)
def Modify():
with open ('StudentRecord.dat','rb') as Myfile:
newRecord=[]
while True:
try:
rec=pickle.load(Myfile)
newRecord.append(rec)
except EOFError:
break
found=1
for i in range(len(newRecord)):
roll =int(input("Enter a Rollno to be update: "))
if newRecord[i]['SROLL']==roll:
name=input("Enter Name: ")
perc=float(input("Enter Percentage: "))
remark=input("Enter Remark: ")
newRecord[i]['SNAME']=name
newRecord[i]['SPERC']=perc
newRecord[i]['SREMARKS']=remark
found =1
else:
found=0
if found==0:
Writerecord()
Modify()
6. Write a random number generator that generates random numbers between 1 and 6
(simulates a dice).
import random
def generate_random_number():
return random.randint(1, 6)
print(generate_random_number())
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()
8. Write a program 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).....")
string=input('Enter a string:')
if string==string[::-1]:
print(string,'is a palindrome.')
else:
print(string,'is not a palindrome.')
10. Find the largest/smallest number in a list
11. WAP to input any two tuples and swap their values.
t1 = tuple()
n = int (input("Total no of values in First tuple: "))
for i in range(n):
a = input("Enter Elements : ")
t1 = t1 + (a,)
t2 = tuple()
m = int (input("Total no of values in Second tuple: "))
for i in range(m):
a = input("Enter Elements : ")
t2 = t2 + (a,)
print("First Tuple : ")
print(t1)
print("Second Tuple : ")
print(t2)
t1,t2 = t2, t1
12. WAP to store students’ details like admission number, roll number, name and percentage in a
dictionary and display information on the basis of admission number.
record = dict ()
i=1
n= int (input ("How many records u want to enter: "))
while(i<=n):
Adm = input("Enter Admission number: ")
roll = input("Enter Roll Number: ")
name = input("Enter Name :")
perc = float(input("Enter Percentage : "))
t = (roll,name, perc)
record[Adm] = t
i=i+1
Nkey = record.keys()
for i in Nkey:
print("\nAdmno- ", i, " :")
r = record[i]
print("Roll No\t", "Name\t", "Percentage\t")
for j in r:
print(j, end = "\t")
13. Write a program with a user-defined function with string as a parameter which replaces all
vowels in the string with ‘*’.
def strep(str):
str_lst =list(str)
for i in range(len(str_lst)):
if str_lst[i] in 'aeiouAEIOU':
str_lst[i]='*'
new_str = "".join(str_lst)
return new_str
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
15. Program to search the record of a particular student from CSV file on the basis of inputted
name.
import csv
number = input('Enter number to find: ')
found=0
with open('Student_Details.csv') as f:
csv_file = csv.reader(f, delimiter=",")
for row in csv_file:
if number ==row[0]:
print (row)
found=1
else:
found=0
if found==1:
pass
else:
print("Record Not found")
16. Write the definition of a method/function SearchOut(Teachers, TName) to search for TName
from a list Teachers, and display the position of its presence.
For example :
If the Teachers contain ["Ankit", "Siddharth", "Rahul", "Sangeeta", "rahul"]
and TName contains "Rahul"
The function should display
Rahul at 2
rahul at 4
def pop_city():
while True:
if stk==[]:
print("underflow")
else:
print(stk.pop())
d={"Tamilnadu":"Chennai","Karnataka":"Bangalore","Goa":"Panaji","Telangana":"Hyderabad"}
push_city(d)
pop_city()
18. Write a menu driven Python Program to perform Arithmetic operations (+,-*,/) based on the
user’s choice.
22. Write a Python Program to integrate MYSQL with Python to create Database and Table to
store the details of employees.
23. Write a Python Program to integrate MYSQL with Python by inserting records to Emp table
and display the records.
24. Write Queries for the following Questions based on the given table:
(b)
26. Write Queries for the following Questions based on the given table:
(b) Change the Region of salesman ‘SHYAM’ to ‘SOUTH’ in the table Salesperson.
UPDATE SALESPERSON SET REGION='SOUTH' WHERE S_NAME="SHYAM";
(c) Delete the record of salesman RISHABH, as he has left the company.
DELETE FROM SALESPERSON WHERE S_NAME="RISHABH";
(a) Add the constraint, primary key to column P_id in the existing table Projects
(b) To change the language to Python of the project whose id is P002
(c) Remove an attribute Enddate from the table.
(d) To delete the table Projects from MySQL database along with its data
28. Write Queries for the following Questions based on the given table:
29. Write Queries for the following Questions based on the given table:
(a) To display details of all the items in the STORE table in ascending order of LastBuy.
(b) To display ItemNo and Item name of those items from STORE table, whose Rate is more than
15.
(c) To display the details of those items whose Supplier code (Scode) is 22 or Quantity in Store
(Qty) is more than 110 from the table STORE.
(d) Remove the column “Rate”
31. Write Queries for the following Questions based on the given table:
32. Write Queries for the following Questions based on the given table:
(a) To show all information about the Baby cot from the INTERIORS table.
(b) To list the ITEMNAME, which are priced at more than 10000 from the INTERIORS table.
(c) To list ITEMNAME and TYPE of those items, in which DATEOFSTOCK is before 22/01/02 from
the INTERIORS table in descending order of ITEMNAME.
(d) To insert a new row in the INTERIORS table with the following data
{14, ‘TrueIndian’, ‘Office Table’, ‘25/03/03’, 15000, 20}
34. Write Queries for the following Questions based on the given table:
35. Write Queries for the following Questions based on the given table:
(a) Write a statement to create the above table.
(b) Display total number of flights.
(c) Display number of flights whose FL_NO starts with “IC”.
(d) Show the maximum number of stops.