0% found this document useful (0 votes)
31 views18 pages

CS - Lab Practical

Kndkd
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)
31 views18 pages

CS - Lab Practical

Kndkd
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/ 18

1. Read a text file line by line and display each word separated by a #.

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:

print("Record not found")


with open ('StudentRecord.dat','wb') as Myfile:
for j in newRecord:
pickle.dump(j,Myfile)

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())

7. Write a python program to implement a stack using a list data-structure.

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).....")

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


readcsv=csv.reader(fileobject)
for i in readcsv:
print(i)

9. Input a string and determine whether it is a palindrome or not.

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

# creating empty list


list1 = []

# asking number of elements to put in list


num = int(input("Enter number of elements in list: "))

# iterating till num to append elements in list


for i in range(1, num + 1):
ele= int(input("Enter elements: "))
list1.append(ele)

# print maximum element


print("Largest element is:", max(list1))

# print minimum element


print("Smallest element is:", min(list1))

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

print("After Swapping: ")


print("First Tuple : ")
print(t1)
print("Second Tuple : ")
print(t2)

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

line = input("Enter string: ")


print("Orginal String")
print(line)
print("After replacing Vowels with '*'")
print(strep(line))

14. Recursively find the factorial of a natural number.

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)

n = int(input("Enter any number: "))


print("The factorial of given number is: ",factorial(n))

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 SearchOut(Teachers, TName):


for i in range(len(Teachers)):
if TName==Teachers[i]:
print(Teachers[i],"at",i)
elif TName.lower()==Teachers[i]:
print(Teachers[i],"at",i)

Teachers=["Ankit", "Siddharth", "Rahul", "Sangeeta", "rahul"]


TName="Rahul"
SearchOut(Teachers, TName)

17. A dictionary, d_city contains the records in the following format :


{state:city}
Define the following functions with the given specifications :
(i) push_city(d_city): It takes the dictionary as an argument and pushes all the cities in
the stack CITY whose states are of more than 4 characters.
(ii) pop_city(): This function pops the cities and displays "Stack empty" when there are
no more cities in the stack.
stk=[]
def push_city(d_city):
for k,v in d_city.items():
if len(k)>4:
stk.append(v)

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.

19. Write a Python Program to display Fibonacci Series up to ‘n’ numbers.


20. Write a Python program to define the function Check(no1,no2) that take two numbers and
Returns the number that has minimum ones digit.

Write a Python program to implement python mathematical functions to find:

(i) To find Square of a Number.


(ii) To find Log of a Number(i.e. Log10)
(iii) To find Quad of a Number
21. Write a method Disp() in Python, to read the lines from poem.txt and display those words
which are less than 5 characters.

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:

(a) Write a Query to Create a new database in the name of "STUDENTS".


Create database students;

(b) Write a Query to Open the database "STUDENTS".


Use students;

(c) Write a Query to create the above table called: "STU"


CREATE TABLE STU(ROLLNO INT PRIMARY KEY,NAME VARCHAR(10), GENDER VARCHAR(3),
AGE INT,DEPT VARCHAR(15), DOA DATE,FEES INT); Write a Query to insert all the rows of
above table into STU table

(d) Write a Query to select distinct Department from STU table.


SELECT DISTICT(DEPT) FROM STU;
25. Write Queries for the following Questions based on the given table:

(a) Display the total salary received by each designation.


Select designation, sum(salary) from bank group by designation;

(b)

26. Write Queries for the following Questions based on the given table:

(a) Insert details of one salesman with appropriate data.


INSERT INTO SALESPERSON VALUES("S006","JAYA",23,34000,'SOUTH');

(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";

(d) Remove an attribute REGION from the table.


ALTER TABLE SALESPERSON DROP COLUMN REGION;
27. Write Queries for the following Questions based on the given table:

(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:

(a) Delete the records whose language is “English”


(b) Add a new record : “M050”, “Palki”,“Hindi”, 5, “Amazon Prime”
(c) Add a new column “DAYS” of type integer
(d) Remove the column “RATING”

29. Write Queries for the following Questions based on the given table:

(a) Display the number of distinct Scodes.


(b) Display the maximum and minimum quantities.
(c) Display the structure of the STORE table.
(d) Add a new column Location varchar(50) in the table to store the location details of the
items.
30. 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:

(a) Display the average Marks.


(b) Display the different Classes.
(c) Change the data type of Marks column so that it can take fractional values upto 2 decimals.
(d) Increase width of Name column to varchar(50).

32. Write Queries for the following Questions based on the given table:

(a) Add a new column Driver varchar(30)


(b) Change data type of Rate column to float(6,1).
(c) Display the cab type whose rate is more than 25.
(d) Display cab id and Number of passengers for cab sedan.
33. 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:

(a) Write a statement to create the above table


(b) Write a command to change the width of Customer column to varchar(30)
(c) Display the field names, their type , size and constraints .
(d) Display details of orders where orderprice is in the range 500 to 1500

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.

You might also like