Class 12 Computer Science Practicals
Class 12 Computer Science Practicals
SCHOOL
Computer Sc.
PRACTICAL FILE
2023-24
Submitted by:
RollNo: Cbse Roll No.
NAME: VAIBHAV RAJ
CLASS/SEC: 12TH C
Submitted To:
1. Push
2. Pop
3. Display
4. Exit
17. Julie has created a dictionary containing
names and marks as key value pairs of 6
students. Write a program, with
separate user defined functions to
perform the following operations:
● Push the keys (name of the student) of
the dictionary into a stack, where the
corresponding value (marks) is greater
than 75.
● Pop and display the content of the
stack. For example: If the sample
content of the dictionary is as follows:
R={"OM":76, "JAI":45, "BOB":89,
"ALI":65, "ANU":90, "TOM":82} The
output from the program should be:
TOM ANU BOB OM
Ques :26 Consider the table CLUB given below and write
the output of the SQL queries that follow.
Ans:
Question 1:
Write a program using function convert that takes a string with
multiple words and then capitalizes the first letter of each word and
forms a new string out of it.
CODING:
def convert(input_string):
# Split the input string into a list of words
words = input_string.split()
# Initialize an empty list to store the capitalized words
capitalized_words = []
# Iterate through the words and capitalize the first letter of each word
for word in words:
capitalized_word = word.capitalize()
capitalized_words.append(capitalized_word)
# Join the capitalized words to form a new string
new_string = ' '.join(capitalized_words)
return new_string
# Input string with multiple words
input_string = input(“ enter string :”)
# Call the convert function and print the result
result = convert(input_string)
print(result)
OUTPUT:
Question 2:
Write a random number generator that generate random nos
between 1 and 6(simulates a dice)
Coding:
import random
def roll_dice():
# Generate a random number between 1 and 6 (inclusive)
return random.randint(1, 6)
OUTPUT:
Question 3:
Write a Program to check if the entered number is Armstrong or not.
Coding:
num=int(input("enter a number :"))
sum=0
temp = num
while temp > 0:
digit=temp % 10
sum += digit**3
temp //=10
if num == sum :
print(num,"is an armstrong number ")
else:
print(num,"is not armstrong number ")
OUTPUT:
Question 4:
Write a program to define a function prime which input a Number
and check whether it is prime or not.
Coding:
def prime():
n=int(input('Enter a number:'))
for i in range(2,n):
if n%i==0:
print(n,' is not a prime no.')
else:
print(n,' is a prime no.')
break
prime()
OUTPUT:
Question 5:
Write a Program to enter the string and to check if it's
palindrome or not using loop.
Coding:
def is_palindrome(input_string):
input_string = input_string.replace(" ", "").lower()
left = 0
right = len(input_string) - 1
while left < right:
if input_string[left] != input_string[right]:
return False
left += 1
right -= 1
return True
user_input = input("Enter a string: ")
if is_palindrome(user_input):
print(f"{user_input} is a palindrome.")
else:
print(f"{user_input} is not a palindrome.")
OUTPUT:
Question 6:
Count and display the number of vowels, consonants,
uppercase, lowercase characters in string.
Coding:
def count_characters(input_string):
vowels = 0
consonants = 0
uppercase = 0
lowercase = 0
vowel_set = set("aeiouAEIOU")
for char in input_string:
if char.isalpha():
if char in vowel_set:
vowels += 1
else:
consonants += 1
if char.isupper():
uppercase += 1
elif char.islower():
lowercase += 1
return vowels, consonants, uppercase, lowercase
user_input = input("Enter a string: ")
vowels,consonants,uppercase,lowercase=count_characters(us
er_input)
print(f"Number of vowels: {vowels}")
print(f"Number of consonants: {consonants}")
print(f"Number of uppercase characters: {uppercase}")
print(f"Number of lowercase characters: {lowercase}")
OUTPUT:
Question7:
Write a Program to store students information like admission
number, roll number, name, marks in a dictionary and display
information on the basis of admission number.
Coding:
student_info = {}
def add_student(admission_number, roll_number, name, marks):
student_info[admission_number] = {'Roll Number': roll_number,'Name':
name,'Marks': marks}
def display_student_info(admission_number):
student = student_info.get(admission_number)
if student:
print("Student Information:")
print(f"Admission Number: {admission_number}")
for key, value in student.items():
print(f"{key}: {value}")
else:
print(f"Student with Admission Number {admission_number} not found.")
add_student('A001', 'R001', 'keshav', 99)
add_student('A002', 'R002', 'pushkar', 89)
add_student('A003', 'R003', 'eva', 78)
display_student_info(search_admission_number)
OUTPUT:
Question 8:
Write a function fibo(n) to compute the Fibonacci Series upto
nth no. .
Coding:
def fibo(n):
# Initialize the first two Fibonacci numbers
fibonacci_sequence = [0, 1]
return fibonacci_sequence
OUTPUT:
Question 9:
Write a Program to create a text file Story.txt and write a story
in it. Also read the file and display its content line by line and
display its content.
Coding:
with open("Story.txt", "w") as file:
story = " A farmer asked his son to take their herd of sheep
grazing every day.
While the boy watched over the sheep, he got bored and decided
to have some fun.
So, he shouted, “Wolf! Wolf!”. Upon hearing this the villagers ran
to help him chase the Wolf away.
As they reached him, they realized that there was no Wolf and he
was just kidding. The villagers were furious and they yelled at the
boy for creating chaos and panic.
On the next day and the boy shouted “Wolf!” again and once
again the villagers came to help him and saw that there was no
wolf. This made them very angry again.
On the same day, the boy saw an actual Wolf that has terrorizing
the sheep. The boy cried “Wolf! Wolf! please help me” and no
villagers showed up as they believed that the boy was joking
again"""
file.write(story)
with open("Story.txt", "r") as file:
print("Content of 'Story.txt':")
for line in file:
print(line.strip())
OUTPUT:
Question 10:
Write a Program to read story.txt (the above file) and display the
number of vowels, consonants, uppercase and lowercase letters in
the file.
Coding:
fobj=open('story.txt','r+’)
content=fobj.read()
vowel =consonant=lowercase=uppercase=0
for i in content :
if i=='a' or i=='e' or i=='i' or i=='0' or i=='u' or i=='A' or i=='E' or
i=='l' or i=='0' or i=='U':
vowel+=1
elif ==" ":
pass
else:
consonant+=1
if i.isupper():
uppercase+=1
if i.islower():
lowercase+=1
print('Total no. of vowels’,vowel)
print('Total no. of consonent=',consonant)
print('Total no. of uppercase=',uppercase)
print("Total no. of lowercase “,lowercase)
fobj.close()
OUTPUT:
Question 11
Write a Program to read lines from a file kamal.txt and remove all the
lines that starts with 'a' in a file and write it to another file kms.txt.
Coding:
fobj=open("kamal.txt”, 'w')
fobj.write(“Kamal Model Sr. Sec. School")
fobj.write('It is one of the best school of west delhi sidtrict. \n It
is affilated by cbse. \n The school is for all students from class
nursery to class 12th . \n A school with lot good teachers.’)
fobj.close()
l=[]
l1=[]
fobj=open('kamal.txt','r')
while True:
s=fobj.readline()
if s==’ ‘ :
break
elif s[0].upeer()=='A':
l.append(s)
else:
l1..append(s)
fobj.close()
fobj=open('kamal.txt', 'w')
for i in l1:
fobj.write(i)
fobj.close()
fobj1=open('kms.txt', 'w')
for j in l:
fobj1.write(j)
fobj1.close()
OUTPUT:
Question 12:
Create a binary file student.dat with having each record [rollno, name
and fees). Search for a rollno and display the corresponding record. If
not found display message "The record does not found'. The Menu of
the program will be as follows
1. Create binary file
2. Display Content
3. Search for a roll no and display the record
4. Exit
Coding:
import pickle
def insert_record():
try:
with open("student.dat", "ab") as file:
rollno = input("Enter Roll Number: ")
name = input("Enter Name: ")
marks = float(input("Enter Marks: "))
record = {'Rollno': rollno, 'Name': name, 'Marks': marks}
pickle.dump(record, file)
print("Record inserted successfully.")
except Exception as e:
print(f"An error occurred: {e}")
def read_records():
try:
with open("student.dat", "rb") as file:
print("Records in 'student.dat':")
while True:
try:
record = pickle.load(file)
print(f"Roll Number: {record['Rollno']}, Name: {record['Name']},
Marks: {record['Marks']}")
except EOFError:
break
except FileNotFoundError:
print("The file 'student.dat' does not exist.")
def update_record():
try:
with open("student.dat", "rb") as file:
records = []
rollno_to_update = input("Enter Roll Number to update: ")
found = False
while True:
try:
record = pickle.load(file)
if record['Rollno'] == rollno_to_update:
found = True
print(f"Current Record: Roll Number: {record['Rollno']}, Name:
{record['Name']}, Marks: {record['Marks']}")
new_name = input("Enter New Name (press Enter to keep it
unchanged): ")
new_marks = input("Enter New Marks (press Enter to keep it
unchanged): ")
if new_name:
record['Name'] = new_name
if new_marks:
record['Marks'] = float(new_marks)
print("Record updated successfully.")
records.append(record)
except EOFError:
break
if not found:
print("Record not found.")
with open("student.dat", "wb") as update_file:
for rec in records:
pickle.dump(rec, update_file)
except FileNotFoundError:
print("The file 'student.dat' does not exist.")
def search_record():
try:
with open("student.dat", "rb") as file:
rollno_to_search = input("Enter Roll Number to search: ")
found = False
while True:
try:
record = pickle.load(file)
if record['Rollno'] == rollno_to_search:
found = True
print(f"Record found: Roll Number: {record['Rollno']}, Name:
{record['Name']}, Marks: {record['Marks']}")
except EOFError:
break
if not found:
print("Record not found.")
except FileNotFoundError:
print("The file 'student.dat' does not exist.")
def delete_record():
try:
with open("student.dat", "rb") as file:
records = []
rollno_to_delete = input("Enter Roll Number to delete: ")
found = False
while True:
try:
record = pickle.load(file)
if record['Rollno'] == rollno_to_delete:
found = True
print(f"Record deleted: Roll Number: {record['Rollno']}, Name:
{record['Name']}, Marks: {record['Marks']}")
else:
records.append(record)
except EOFError:
break
if not found:
print("Record not found.")
with open("student.dat", "wb") as update_file:
for rec in records:
pickle.dump(rec, update_file)
except FileNotFoundError:
print("The file 'student.dat' does not exist.")
while True:
print("\nMenu:")
print("1. Insert a new record")
print("2. Read all records")
print("3. Update a record")
print("4. Search for a record")
print("5. Delete a record")
print("6. Exit")
choice = input("Enter your choice: ")
if choice == '1':
insert_record()
elif choice == '2':
read_records()
elif choice == '3':
update_record()
elif choice == '4':
search_record()
elif choice == '5':
delete_record()
elif choice == '6':
print("Exiting the program.")
break
else:
print("Invalid choice. Please choose a valid option.")
OUTPUT:
Question 13.
Write a menu-driven program to perform all the basic operations using
dictionary on file student.dat binary file. Each record contain Rolino, Name
and Marks. Do the following operation such as insert record, reading record,
update record, search a record and delete a record.
Coding:
import pickle
def insert():
while True:
fobj=open('student.dat','ab')
rollno=int(input("enter roll number:"))
name=input("enter name:")
marks=int(input("enter marks:"))
d={'roll_no':rollno, 'name': name, 'marks': marks}
pickle.dump(d,fobj)
print("record inserted")
fobj.close()
x=input("do you want more records(y/n)")
if x=="n" or x=="N":
break
def read():
fobj=open('student.dat','rb')
while True:
try:
x=pickle.load(fobj)
print(x)
except EOFError:
break
fobj.close()
def search():
file =open("student.dat","rb")
x=int(input("enter roll no:"))
try:
while True:
emp = pickle.load(file)
if emp['roll_no']==x:
print(emp)
except EOFError:
pass
file.close()
def update():
file = open("student.dat","rb")
x=int(input("enter roll no:"))
try:
while True:
emp = pickle.load(file)
if emp['roll_no']== x:
k=int(input("what do you want to change:1.name, 2
marks::"))
if k==1:
n=input("enter new name:")
dec={'name':n}
emp.update(dec)
print("record updated",emp)
elif k==2:
m=input("enter new marks:")
sec={'marks':m}
emp.update(sec)
print("record updated",emp)
ch=input("do you want to change more records(y/n)")
if ch=="n" or ch=="N":
break
except EOFError:
pass
file.close()
def delete():
file= open("student.dat","rb")
x=int(input("enter roll no:"))
try:
while True:
emp =pickle.load(file)
if emp['roll_no']==x:
emp.clear()
print("data deleted sucessfully")
except EOFError:
pass
file.close()
def main():
while True:
choice=int(input("1.Insert 2 Read 3.Search 4.Update 5.Delete
6.Exit:"))
if choice==1:
insert()
elif choice==2:
read()
elif choice==3:
search()
elif choice==4:
update()
elif choice==5:
delete()
elif choice==6:
break
else:
print('Invalid choice')
main()
OUTPUT:
Question 14:
Write a menu-driven program implementing user-defined functions
to perform different functions on a csv file "student" such as:
(a) Write a single record to csv
(b) Write all the records in one single go onto the csv. (c) Display the
contents of the csv file.
Coding:
import csv
fobj=open("student.csv",'a')
csvobj= csv.writer(fobj)
header=['roll number', 'name', 'marks']
csvobj.writerow(header)
def insert_row():
fobj=open("student.csv",'a')
csvobj=csv.writer(fobj)
roll=input("enter roll number:")
name=input("enter name:")
marks=input("enter marks:")
rec=[roll,name,marks]
csvobj.writerow(rec)
fobj.close()
def insert_rows():
fobj=open("student.csv",'a')
csvobj=csv.writer(fobj)
record=[]
while True:
roll=input("enter roll number:")
name=input("enter name:")
marks =input("enter marks:")
rec=[roll,name,marks]
record.append(rec)
ch=input("do you want to insert more records(y/n)")
if ch=="n" or ch=="N":
break
csvobj.writerows(record)
fobj.close()
def display():
fobj=open('student.csv')
csvobj= csv.reader(fobj)
for rec in csvobj:
print(rec)
fobj.close()
while True:
ch=input("1.write one record 2.write more than one record 3. display 4.exit")
if ch=="1":
insert_row()
if ch=="2":
insert_rows()
if ch=="3":
display()
if ch=="4":
break
OUTPUT:
Question15:
Create a CSV file school.txt by entering user-id and password,
read and search the password for given user id.
Coding:
import csv
fobj=open("school.csv","a")
csvobj=csv.writer(fobj)
header=['user_id', 'password']
csvobj.writerow(header)
def insert():
fobj=open("school.csv","a")
csvobj=csv.writer(fobj)
user_id=input("enter user_id:")
password=input("enter password:")
rec=[user_id,password]
csvobj.writerow(rec)
fobj.close()
def display():
fobj=open('school.csv','r')
csvobj=csv.reader(fobj)
for rec in csvobj:
print(rec)
fobj.close()
def search():
fobj=open('school.csv','r')
csvobj=csv.reader(fobj)
x=input("enter user id")
for rec in csvobj:
if rec[0]==x:
print(rec)
else:
print("record not found")
fobj.close()
while True:
ch=input("1.write record 2.display 3.search4.exit")
if ch=="1":
insert()
if ch=="2":
display()
if ch=="3":
search()
if ch=="4":
break
OUTPUT:
Question 16.
Write a Python program to implementall basic operations of a stack,
such as adding element (PUSH operation), removing element (POP
operation) and displaying the stack elements (Traversal operation)
using lists.
1. Push
2. Pop
3. Display
4. Exit
Coding:
s=[]
top=0
def push():
global s,top
ele=input('Enter element to be pushed:')
s.append(ele)
top+=1
def pop():
global s,top
if s==[]:
print("Underflow")
return
d=s.pop()
top=top-1
print("The popped element = ",d)
def display():
global stop
if s==[]:
print('Stack is empty')
return
for i in range(len(s)-1,-1,-1):
print(s[i])
while True:
print('1.Push')
print('2.Pop')
print('3.Display')
print('4.Exit')
ch=int(input('Enter your choice:'))
if ch==1:
push()
elif ch==2:
pop()
elif ch==3:
display()
else:
break
OUTPUT:
Question 17:
Julie has created a dictionary containing names and marks as key
value pairs of 6 students. Write a program, with separate user
defined functions to perform the following operations:
Push the keys (name of the student) of the dictionary into a stack,
where the corresponding value (marks) is greater than 75. • Pop and
display the content of the stack. For example: If the sample content
of the dictionary is as follows:
R={"OM":76, "JAI":45, "BOB":89,"ALI":65, "ANU":90, "TOM":82)
The output from the program should be:
TOM ANU BOB OM
Coding:
d={'OM':76, 'JAI': 45, 'BOB' :89, 'ALI':65, 'ANU': 90, 'TOM':82}
s=[]
def push(s,ele):
s.append(ele)
def pop(s):
if s==[]:
print('Underflow')
return None
return s.pop()
for i in d:
if d[i]>75:
push(s,i)
while True:
if s==[]:
break
print(pop(s), end=' ')
OUTPUT:
Question 18.
Alam has a list containing 10 integers. You need to help him create a
program with separate user defined functions to perform the
following operations based on this list.
-Traverse the content of the list and push the even numbers into a
stack.
-Pop and display the content of the stack.
For Example: If the sample Content of the list is as follows: N=[12, 13,
34,56, 21, 79, 98, 22, 35, 38] Sample Output of the code should be: 38
22 98 56 34 12
Coding:
N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
s=[]
def push(s,ele):
s.append(ele)
def pop(s):
if s==[]:
print("Underflow")
return None
return s.pop()
for i in N:
if i%2==0:
push(s,i)
while True:
if s==[]:
break
print(pop(s),end=' ')
OUTPUT:
Question 19.
WRITE A MENU-DRIVEN PROGRMA CONNECTING WITH MYSQL
MENU:-
1.CREATE A DATABASE 2.SHOW ALL DATABASES
3.CREATE A TABLE 4.INSERT A RECORD
5.UPDATE A RECORD 6.DELETE A RECORD
7.DISPLAY THE RECORDS 8.EXIT
Coding:
import mysql.connector
mydb =
mysql.connector.connect(host="localhost",user="root",pa
ssword="12345")
mycursor =mydb.cursor()
def create_database():
mycursor.execute("CREATE DATABASE school")
print("Database created")
def create_table():
mycursor.execute('use school')
mycursor.execute("CREATE TABLE students(name
VARCHAR(15),address VARCHAR(25))")
print("Table created")
def show_database():
mycursor.execute('use school')
mycursor.execute('SHOW DATABASES')
for i in mycursor:
print(i)
def insert():
name=input("enter name")
add =input("enter address")
sql=("INSERT INTO students(name, address) VALUES (%s,
%s)")
val = (name, add)
mycursor.execute('use school')
mycursor.execute(sql, val)
mydb.commit()
def update():
ad1=input("enter name")
ad2=input("enter new address")
sql = "UPDATE students SET address = %s WHERE name=
%s"
val=(ad2,ad1)
mycursor.execute('use school')
mycursor.execute(sql,val)
mydb.commit()
def delete():
adx=input("enter name")
sql = "DELETE FROM students WHERE name=%s"
val=(adx,)
mycursor.execute('use school')
mycursor.execute(sql,val)
mydb.commit()
def display():
sql = "SELECT * FROM students"
mycursor.execute('use school')
mycursor.execute(sql)
for i in mycursor:
print(i)
while True:
ch=int(input(" 1.CREATE A DATABASE\n 2 SHOW ALL
DATABASES\n 3.CREATE A TABLE\n 4.INSERT A RECORD\
n 5.UPDATE A RECORD\n 6.DELETE A RECORD\n
7.DISPLAY THE RECORDS\n 8.EXIT.\n Please enter your
choice:"))
if ch==1:
create_database()
elif ch==2:
show_database()
elif ch==3:
create_table()
elif ch==4:
insert()
elif ch==5:
update()
elif ch==6:
delete()
elif ch==7:
display()
elif ch==8:
break
OUTPUT:
Question 20
Write a program to insert a record into the table using
Python Interface.
Coding:
import mysql.connector
mydb=mysql.connector.connect(host="localhost",us
er="root",passwd='12345',database='schl')
mycursor=mydb.cursor()
mycursor.execute("INSERT INTO STUDENTTS
VALUES(1,'yash',30)")
sql = "SELECT * FROM studentts"
mycursor.execute(sql)
for i in mycursor:
print(i)
print("Record Inserted Successfully!!!! ")
mydb.commit()
OUTPUT:
Question 21.
Write a python program that displays first three rows
fetched from student table of Mysql database "school".
Use mysql.connector to connect with the database.
Coding:
import mysql.connector
mydb=mysql.connector.connect(host="localhost",
user="root",passwd="12345",database="school")
mycursor=mydb.cursor()
mycursor.execute('use school')
mycursor.execute('SELECT *FROM STUDENT')
x=mycursor.fetchmany(3)
for i in x:
print(i)
mydb.commit()
OUTPUT:
Question 22.
Write a Python program to displays all the records from
student table of MySQL database "school".
Coding:
import mysql.connector
mydb=mysql.connector.connect(host="localhost",us
er="root",passwd= "12345",database="school")
mycursor=mydb.cursor()
mycursor.execute('SELECT * FROM STUDENT')
x=mycursor.fetchall()
for i in x:
print(i)
OUTPUT:
Question 23.
Perform all the operations like insert record, display record,
update record and delete record with reference to table
'Employee' having field empno, ename, sal where empno is
primary key, through MySQL-Python connectivity.
Coding:
import mysql.connector
mydb=mysql.connector.connect(host="localhost",us
er="root",passwd="12345",database="school")
mycursor=mydb.cursor()
def insert_record():
no= input("enter eno: ")
name=input("enter name: ")
sal=input("enter salary: ")
val= (no,name,sal)
mycursor.execute("INSERT INTO
employee(empno,ename,sal) VALUES (%s, %s,
%s)",val)
mydb.commit()
def display_record():
mycursor.execute("SELECT * FROM employee")
x=mycursor.fetchall()
for i in x:
print(i)
def update_record():
eno=int(input('enter empno whose details to be
updated'))
name=input('enter new name')
val=(name,eno)
mycursor.execute("UPDATE employee SET ename=
%s WHERE empno=%s",val)
mydb.commit()
def delete_record():
eno=int(input('enter empno whose details to be
deleted'))
val=(eno,)
mycursor.execute("DELETE FROM Employee
WHERE empno=%s",val)
mydb.commit()
while True:
ch=int(input(" 1.INSERT A RECORD\n 2.DISPLAY
THE RECORDS\n 3 UPDATE A RECORD\n 4.DELETE A
RECORD\n Enter your choice : "))
if ch==1:
insert_record()
elif ch==2:
display_record()
elif ch==3:
update_record()
elif ch==4:
delete_record()
else:
break
OUTPUT:
Question 24.
write program to input two numbers and find out quotient.
handle exception like valueerror, zerodivisionerror. in your
code else and finally should also be there
Coding:
try:
a = int(input('Enter first number: '))
b = int(input('Enter second number: '))
quotient = a // b
print('The quotient of {} and {} is {}'.format(a, b,
quotient))
except ValueError:
print('Invalid input. Please enter two valid numbers.')
except ZeroDivisionError:
print('Cannot divide by zero.')
OUTPUT:
QUESTION 25.
SQL (25 QUERIES)
1. Create Database say_school in mysql.
CODE- create database school;