You are on page 1of 18

Roll no:

CS BOARD PRACTICAL – CLASS XII

TIME:. M.M -15

General Instructions:
1. All questions are compulsory.
2. All questions carry equal marks (5 marks each).
3. All questions are divided into 2 parts (2.5 marks each).
4. All programming questions are to be answered using Python
Language only.

Q 1. Create a Binary File 'employee.dat' containing records of


Employee ID, Employee name and Employee Salary. Update a
record in the file.
Solution: # Imports Pickle Module
import pickle as p

# Adds New Records


def add_records():
f = open('employee.dat', 'wb')
n = int(input("Enter No. of Records: "))
for i in range(n):
print(f"Details of Employee {i+1}:")
empid = int(input("Enter ID: "))
name = input("Enter Name: ")
salary = float(input("Enter Salary: "))
print()
data = [empid, name, salary]
p.dump(data, f)
print('Done.')
f.close()

# Displays Records
def display_records():
f = open('employee.dat', 'rb')
try:
while True:
x = p.load(f)
print(x)
except EOFError:
print("Complete Data Read Successfully.")
print()
f.close()

# Update a Record
def update_record():
f = open('employee.dat', 'ab+')
f.seek(0)
empid = int(input("Enter ID of record to update: "))
try:
while True:
x = f.tell()
l = p.load(f)
if l[0] == empid:
f.seek(x)
print("Found Record:")
newid = int(input("Update ID: "))
name = input("Update Name: ")
salary = float(input("Update Salary: "))
data = [newid, name, salary]
p.dump(data, f)
print("Record Updated.")
f.close()
break
except EOFError:
print("Error 404: Record Not Found")
f.close()
# Function Calls
add_records()
display_records()
update_record()
display_records()
Q 2. Write a python program to create a binary file with name and
roll number. Search for a given roll number and display name, if not
found display appropriate message.
Solution: import pickle as p

with open('stu-details.dat', 'wb') as f:


n = int(input("Enter No. of Students to add: "))
for i in range(n):
print(f"Details of Student {i+1}:")
roll = int(input("Enter Roll No.: "))
name = input("Enter Name: ")
print()
data = [roll, name]
p.dump(data, f)
print("Done.")

with open('stu-details.dat', 'rb') as f:


roll = int(input("Enter Roll No. to search: "))
try:
while True:
l = p.load(f)
if l[0] == roll:
print("Found:", l[1])
break
except EOFError:
print("Roll No. not found.")

Q 3. Write a python program to create a binary file with roll


number, name and marks. Input a roll number and update name
and marks.
Solution: import pickle as p

with open('stu-file.dat', 'wb') as f:


n = int(input("Enter No. of Students to add: "))
for i in range(n):
print(f"Details of Student {i+1}:")
roll = int(input("Enter Roll No.: "))
name = input("Enter Name: ")
marks = float(input("Enter Marks: "))
print()
data = [roll, name, marks]
p.dump(data, f)
print("Done.")

with open('stu-file.dat', 'rb+') as f:


roll = int(input("Enter Roll No. to update: "))
try:
while True:
d = p.load(f)
t = f.tell()
if d[0] == roll:
name = input("Update Name: ")
marks = float(input("Update Marks: "))
data = [roll, name, marks]
f.seek(t)
p.dump(data, f)
break
except EOFError:
print("Roll No. not found")

Q 4. Write a python program to create a CSV file named “Mycsv.py”


by entering dept-id, name and city, read and search the record for
given dept-id and If found, display the details of the department
else display Department Not Found.
Solution:
import csv
with open('Mycsv.csv', 'w') as f:
n = int(input("Enter No. of Departments to add: "))
w = csv.writer(f)
for i in range(n):
print(f"Details of Department {i+1}:")
dept_id = int(input("Enter Department ID: "))
name = input("Enter Dept Name: ")
city = input("Enter City Name: ")
print()
data = [dept_id, name, city]
w.writerow(data)
print("Done.")
with open('Mycsv.csv', 'r') as f:
r = csv.reader(f)
for i in r:
if i[0] == dept_id:
print('Found Record:', i)
break
else:
print("Department Not Found.")
Q 5. Write a python program to sort elements of a list in ascending
and descending order by using bubble sort. Write user defined
function.
Solution:
input_lst = eval(input("Enter a list of integers: "))

# Function to sort list in ascending order through bubble sort


def bubble_sort_asc(lst):
for i in range(len(lst) - 1):
for j in range(len(lst) - 1 - i):
if lst[j] > lst[j + 1]:
lst[j], lst[j + 1] = lst[j + 1], lst[j]

# Function to srt list in descending order through bubble sort


def bubble_sort_desc(lst):
for i in range(len(lst) - 1):
for j in range(len(lst) - 1 - i):
if lst[j] < lst[j + 1]:
lst[j], lst[j + 1] = lst[j + 1], lst[j]

# Function Calls
print("Original list:", input_lst)
bubble_sort_asc(input_lst)
print("Ascending order:", input_lst)
bubble_sort_desc(input_lst)
print("Descending order:", input_lst)
Q 6. Create a Menu-Driven Program which add data and reads data
on the table Students (StudentID, Name, Course) by using python
mysql connector.
Solution:
import mysql.connector as c
password = input("Enter Password to SQL server: ")
db = c.connect(host="localhost", username="root",
passwd=password)
cursor = db.cursor()
# Create Database and Tables
cursor.execute("CREATE DATABASE IF NOT EXISTS Students;")
cursor.execute("USE Students;")
cursor.execute("CREATE TABLE IF NOT EXISTS Students (StudentID
INTEGER PRIMARY KEY, Name VARCHAR(50) NOT NULL, Course
VARCHAR(50) NOT NULL);")

# adding data into table


def add_data():
print("Adding Row to Table: Students")
stu_id = int(input("Enter Student ID: "))
name = input("Enter Student Name: ")
course = input("Enter Student Course: ")

query = "INSERT INTO Students VALUES({}, '{}',


'{}')".format(stu_id, name, course)
cursor.execute(query)
if cursor.rowcount > 0:
db.commit()
print("Added Row")
else:
print("Could Not Add Row!")
def read_data():
print("Reading Data from Table: Students")
cursor.execute("SELECT * FROM Students;")
data = cursor.fetchall()
print(f"Reading from {cursor.rowcount} rows.")
for i in data:
print(i)
# Menu
while True:
print("""Choose from the following operations:
1. Add New Row
2. Read All Rows
3. EXIT
""")
choice = input("Choose [1/2/3]: ")
print()
if choice == "1":
add_data()
print()
elif choice == "2":
read_data()
print()
elif choice == "3":
print("Exiting...")
break
else:
print("Please Enter Correct Option!")
print()

Q 7. Write a menu driven program in python to delete name of a


student from dictionary and to search phone no of a student by
student name. Create menu as below:
******MENU*******
1. Delete from Dictionary
2. Search Phone number using name from Dictionary
3. Exit
Solution:
# Dictionary Creation and Inputs
student_dict = {}
n = int(input("Enter Number of Students: "))
for i in range(n):
print(f"Enter Details of Student {i+1}:")
name = input(f"Name of Student {i+1}: ")
phone_no = int(input(f"Phone Number of Student {i+1}: "))
student_dict[name.lower()] = phone_no
print()

# Menu
while True:
print("""******MENU*******
1. Delete From Dictionary
2. Search Phone Number using Name from Dictionary
3. Exit
""")
option = input("Choose Action [1/2/3]: ")

if option == "1":
del_name = input("Which students details do you want to
delete: ")
print(f"Deleting {del_name.lower()} Details...")
print(student_dict.pop(del_name.lower(), "Student Not Found!
Try Again."))
print()
elif option == "2":
search_name = input("Which students number do you want to
search: ")
print("Searching...")
print(student_dict.get(search_name.lower(), "Student Not
Found! Try Again."))
print()
elif option == "3":
print("Exiting...")
break
else:
print("Invalid Action! Please Enter Valid Action.")
print()
Q 8. Write a program to read a list of n integers (positive as well as
negative). Create two new lists, one having all positive numbers
with sum and the other having all negative numbers with sum from
the given list.
Solution:
input_lst = eval(input("Enter a list of positive and negative integers:
"))

# Function to create two separate lists of positive and negative


integers with their sum
def positive_negative_sort(lst):
positive_lst = []
positive_sum = 0
negative_lst = []
negative_sum = 0

for i in lst:
if i > 0:
positive_lst.append(i)
positive_sum += i
elif i < 0:
negative_lst.append(i)
negative_sum += i
print("Original List:", input_lst)
print("List of Positive Integers:", positive_lst)
print("Sum of Positive Integers:", positive_sum)
print("List of Negative Integers:", negative_lst)
print("Sum of Negative Integers:", negative_sum)

# Function Call
positive_negative_sort(input_lst)

Q 9. Write a program using python to get 10 players name and their


score. Write the input in a csv file. Accept a player name using
python. Read the csv file to display the name and the score. If the
player name is not found give an appropriate message.
Solution:
importcsv
with open('c:\\pyprg\\player.csv','w') as f:
w = csv.writer(f)
n=1
while (n<=10):
name = input("Player Name?:" )
score = int(input("Score: "))
w.writerow([name,score])
n+=1
print("Player File created")
f.close()
searchname=input("Enter the name to be searched ")
f=open('c:\\pyprg\\player.csv','r')
reader =csv.reader(f)
lst=[]
for row in reader:
lst.append(row)
q=0
for row in lst:
if searchname in row:
print(row)
q+=1
if(q==0):
print("string not found")
f.close()

Q 10. Write a Python program to implement all basic operations of


a stack, such as adding element (PUSH operation), removing
element (POP operation) and displaying the stack elements
(Traversal operation) using lists.

Solution: #Implementation of List as stack


s=[]
c="y"
while (c not in "Yy"):
print ("1. PUSH")
print ("2. POP ")
print ("3. Display")
choice=int(input("Enter your choice: "))
if (choice==1):
a=input("Enter any number :")
s.append(a)
elif (choice==2):
if (s==[]):
print ("Stack Empty")
else:
print ("Deleted element is : ",s.pop())
elif (choice==3):
l=len(s)
for i in range(-1,-l-1,-1): #To display elements from last element
#to first
print (s[i])
else:
print("Wrong Input")
c= input("Do you want to continue (Y/N) : ")

Q 11. Write a program in Python to add, delete and display


elements from a queue using list.
Solution:
#Implementing List as a Queue - using function append() and pop()
a=[]
c='y'
while (c=='y'):
print ("1. INSERT")
print ("2. DELETE ")
print ("3. Display")
choice=int(input("Enter your choice: "))
if (choice==1):
b=int(input("Enter new number: "))
a.append(b)
elif (choice==2):
if (a==[]):
print("Queue Empty")
else:
print ("Deleted element is:",a[0])
a.pop(0)
elif (choice==3):
l=len(a)
for i in range(0,l):
print (a[i])
else:
print("wrong input")
c=input("Do you want to continue or not: ")

You might also like