0% found this document useful (0 votes)
26 views16 pages

CS Practical Exam

The document contains a series of practical exam questions and answers related to programming in Python, covering file operations, data structures, CSV handling, and SQL integration. Each question includes code snippets that demonstrate how to perform specific tasks such as reading files, counting characters, managing student records, and executing SQL commands. The answers are structured to provide clear solutions to the problems posed in the questions.

Uploaded by

purbipatel10107
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)
26 views16 pages

CS Practical Exam

The document contains a series of practical exam questions and answers related to programming in Python, covering file operations, data structures, CSV handling, and SQL integration. Each question includes code snippets that demonstrate how to perform specific tasks such as reading files, counting characters, managing student records, and executing SQL commands. The answers are structured to provide clear solutions to the problems posed in the questions.

Uploaded by

purbipatel10107
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/ 16

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("Mydoc.txt",'r')
for line in filein:
word= line .split()
for w in word:
print(w + '#',end ='')
print()
filein.close()

2. Read a text file and display the number of


vowels/consonants/uppercase/lowercase characters in the file.

Ans:

filein = open("Mydoc1.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.

Ans:

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.

Ans:

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

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 ('StudentRecord.dat','ab') as Myfile:

srecord={"SROLL":sroll,"SNAME":sname,"SPERC":sperc,
"SREMARKS":sremark}
pickle.dump(srecord,Myfile)

def Readrecord():
with open ('StudentRecord.dat','rb') as Myfile:
print("\n-------DISPALY STUDENTS
DETAILS--------")
print("\nRoll No.",' ','Name','\t',end='')
print('Percetage',' ','Remarks')
while True:
try:
rec=pickle.load(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 ('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)):
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)

def main():

while True:
print('\nYour Choices are: ')
print('1.Insert Records')
print('2.Dispaly Records')
print('3.Update Records')
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
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 (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()
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):
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. 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 = csv.DictWriter(file,
fieldnames=["user_id", "password"])

writer.writeheader()

writer.writerows(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 = csv.DictReader(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 = "users.csv"

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 = sqlite3.connect("student.db")
cursor = connection.cursor()

# Step 2: Create table


cursor.execute("""
CREATE TABLE IF NOT EXISTS student (
student_id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER,
marks INTEGER
);
""")

# Step 3: Insert data


cursor.executemany("""
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)
])
connection.commit()

# Step 4: Execute SQL commands


# ALTER TABLE
cursor.execute("ALTER TABLE student ADD COLUMN
gender TEXT;")

# UPDATE
cursor.execute("UPDATE student SET marks = 75
WHERE student_id = 3;")
connection.commit()

# ORDER BY
cursor.execute("SELECT * FROM student ORDER BY
marks ASC;")
print("Students ordered by marks:",
cursor.fetchall())
# DELETE
cursor.execute("DELETE FROM student WHERE marks
< 80;")
connection.commit()

# GROUP BY
cursor.execute("""
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:",
cursor.fetchall())

# Close the connection


connection.close()

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy