C.
S PRACTICAL EXAM QUEs AND
ANS:
1. Read a text file line by line and display each word separated by
a #.
Ans:
filein = open("[Link]",'r')
for line in filein:
word= line .split()
for w in word:
print(w + '#',end ='')
print()
[Link]()
2. Read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file.
Ans:
filein = open("[Link]",'r')
line = [Link]()
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 [Link]():
count_up +=1
if [Link]():
count_low += 1
if ch in 'aeiouAEIOU':
count_vow += 1
if [Link]():
count_con += 1
if [Link]():
count_digit += 1
if not [Link]() 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)
[Link]()
3. Remove all the lines that contain the character 'a' in a file and
write it to another file.
Ans:
f1 = open("[Link]")
f2 = open("[Link]","w")
for line in f1:
if 'a' not in line:
[Link](line)
print('## File Copied Successfully! ##')
[Link]()
[Link]()
f2 = open("[Link]","r")
print([Link]())
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.
Ans:
import pickle
def Writerecord(sroll,sname):
with open ('[Link]','ab') as Myfile:
srecord={"SROLL":sroll,"SNAME":sname}
[Link](srecord,Myfile)
def Readrecord():
with open ('[Link]','rb') as Myfile:
print("\n-------DISPALY STUDENTS
DETAILS--------")
print("\nRoll No.",' ','Name','\t',end='')
print()
while True:
try:
rec=[Link](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 ('[Link]','rb') as Myfile:
while True:
try:
rec=[Link](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('[Link] Records')
print('[Link] Records')
print('[Link] Records (By Roll No)')
print('[Link] (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()
5. Create a binary file with roll number, name and marks. Input a
roll number and update the marks.
Ans:
def Writerecord(sroll,sname,sperc,sremark):
with open ('[Link]','ab') as Myfile:
srecord={"SROLL":sroll,"SNAME":sname,"SPERC":sperc,
"SREMARKS":sremark}
[Link](srecord,Myfile)
def Readrecord():
with open ('[Link]','rb') as Myfile:
print("\n-------DISPALY STUDENTS
DETAILS--------")
print("\nRoll No.",' ','Name','\t',end='')
print('Percetage',' ','Remarks')
while True:
try:
rec=[Link](Myfile)
print(' ',rec['SROLL'],'\t
' ,rec['SNAME'],'\t ',end='')
print(rec['SPERC'],'\t
',rec['SREMARKS'])
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: ")
sperc=float(input("Enter Percentage: "))
sremark=input("Enter Remark: ")
Writerecord(sroll,sname,sperc,sremark)
def Modify(roll):
with open ('[Link]','rb') as Myfile:
newRecord=[]
while True:
try:
rec=[Link](Myfile)
[Link](rec)
except EOFError:
break
found=1
for i in range(len(newRecord)):
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 ('[Link]','wb') as Myfile:
for j in newRecord:
[Link](j,Myfile)
def main():
while True:
print('\nYour Choices are: ')
print('[Link] Records')
print('[Link] Records')
print('[Link] Records')
print('[Link] (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
update: "))
Modify(r)
else:
break
main()
6. Write a random number generator that generates random
numbers between 1 and 6 (simulates a dice).
Ans:
import random
import random
def roll_dice():
print ([Link](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()
7. Write a Python program to implement a stack using list.
Ans:
def isempty(stk):
if stk==[]:
return True
else:
return False
def push(stk,item):
[Link](item)
top=len(stk)-1
def pop(stk):
if isempty(stk):
return "underflow"
else:
item=[Link]()
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
[Link]
[Link]
[Link]
[Link]
[Link]''')
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. Create a CSV file by entering user-id and password, read and
search the password for given userid.
Ans:
import csv
# Step 1: Create a CSV file with user IDs and
passwords
def create_csv(filename):
data = [
{"user_id": "user1", "password":
"password123"},
{"user_id": "user2", "password":
"mypassword456"},
{"user_id": "user3", "password":
"securepass789"},
with open(filename, mode='w', newline='') as
file:
writer = [Link](file,
fieldnames=["user_id", "password"])
[Link]()
[Link](data)
# Step 2: Read the CSV file and search for a
password by user ID
def search_password(filename, search_user_id):
with open(filename, mode='r') as file:
reader = [Link](file)
for row in reader:
if row["user_id"] == search_user_id:
return f"Password for
{search_user_id}: {row['password']}"
return "User ID not found."
# Main execution
csv_filename = "[Link]"
create_csv(csv_filename)
# Search for a password
user_id_to_search = input("Enter user ID to search:
")
result = search_password(csv_filename,
user_id_to_search)
print(result)
9. Create a student table and insert data. Implement the
following SQL commands on the student table:
ALTER table to add new attributes / modify data type /
drop attribute
Ans:
Add new attributes-
ALTER TABLE student ADD COLUMN gender
VARCHAR(10);
Modify data type-
ALTER TABLE student MODIFY COLUMN marks FLOAT;
Drop attribute-
ALTER TABLE student DROP COLUMN gender;
UPDATE table to modify data
Ans: UPDATE student
SET marks = 75
WHERE student_id = 3;
ORDER By to display data in ascending / descending
order
Ans:
Ascending-
SELECT * FROM student
ORDER BY marks ASC;
Decending-
SELECT * FROM student
ORDER BY age DESC;
DELETE to remove tuple(s)
Ans: DELETE FROM student
WHERE student_id = 5;
GROUP BY and find the min, max, sum, count and
average
Ans: SELECT age,
MIN(marks) AS min_marks,
MAX(marks) AS max_marks,
SUM(marks) AS total_marks,
COUNT(*) AS student_count,
AVG(marks) AS avg_marks
FROM student
GROUP BY age;
10. Integrate SQL with Python by importing suitable module
Ans:
import sqlite3=
# Step 1: Connect to the database
connection = [Link]("[Link]")
cursor = [Link]()
# Step 2: Create table
[Link]("""
CREATE TABLE IF NOT EXISTS student (
student_id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER,
marks INTEGER
);
""")
# Step 3: Insert data
[Link]("""
INSERT INTO student (student_id, name, age,
marks)
VALUES (?, ?, ?, ?);
""", [
(1, 'Alice', 20, 85),
(2, 'Bob', 22, 90),
(3, 'Charlie', 19, 70),
(4, 'Diana', 21, 95),
(5, 'Eve', 20, 88)
])
[Link]()
# Step 4: Execute SQL commands
# ALTER TABLE
[Link]("ALTER TABLE student ADD COLUMN
gender TEXT;")
# UPDATE
[Link]("UPDATE student SET marks = 75
WHERE student_id = 3;")
[Link]()
# ORDER BY
[Link]("SELECT * FROM student ORDER BY
marks ASC;")
print("Students ordered by marks:",
[Link]())
# DELETE
[Link]("DELETE FROM student WHERE marks
< 80;")
[Link]()
# GROUP BY
[Link]("""
SELECT age,
MIN(marks) AS min_marks,
MAX(marks) AS max_marks,
SUM(marks) AS total_marks,
COUNT(*) AS student_count,
AVG(marks) AS avg_marks
FROM student
GROUP BY age;
""")
print("Grouped data with aggregates:",
[Link]())
# Close the connection
[Link]()