CLASS-XII
SUBJECT – COMPUTER SCIENCE (083)
PRACTICAL FILE (SESSION 2024-25)
PRACTICAL
NO. PROGRAMS
1. Write a program to check a number whether it is palindrome or not.
num=int(input("Enter a number : "))
n=num
res=0
while num>0:
rem=num%10
SOURCE res=rem+res*10
CODE: num=num//10
if res==n:
print("Number is Palindrome")
else:
print("Number is not Palindrome")
OUTPUT:
2. Write a program to display ASCII code of a character and vice versa.
var=True
while var:
choice=int(input("Press-1 to find the ordinal value of a character \nPress-2 to
find a character of a value\n"))
if choice==1:
ch=input("Enter a character : ")
print(ord(ch))
elif choice==2:
val=int(input("Enter an integer value: "))
SOURCE
CODE:
print(chr(val))
else:
print("You entered wrong choice")
print("Do you want to continue? Y/N")
option=input()
if option=='y' or option=='Y':
var=True
else:
var=False
Press-1 to find the ordinal value of a character
OUTPUT: Press-2 to find a character of a value
1
Enter a character : a
97
Do you want to continue? Y/N
Y
Press-1 to find the ordinal value of a character
Press-2 to find a character of a value
2
Enter an integer value: 65
A
Do you want to continue? Y/N
the user. 1+
3.
1/1!+1/2!+1/3!+⋯+1/n!
def fact(x):
j=1
res=1
while j<=x:
SOURCE
CODE:
res=res*j
j=j+1
return res
n=int(input("enter the number : "))
i=1
sum=1
while i<=n:
f=fact(i)
sum=sum+1/f
i+=1
print(sum)
enter the number : 6
OUTPUT:
7.0
Write a program to read a text file line by line and display each word
4.
separated by '#'.
fin=open("D:\\python programs\\Book.txt",'r')
L1=fin.readlines( )
s=' '
for i in range(len(L1)):
SOURCE L=L1[i].split( )
CODE: for j in L:
s=s+j
s=s+'#'
print(s)
fin.close( )
Text in file:
hello how are you?
python is case-sensitive language.
OUTPUT:
Output in python shell: hello#how#are#you?
#python#is#case-sensitive#language.#
5. Write a program to count the number of vowels present in a text file.
fin=open("D:\\python programs\\MyBook.txt",'r')
str=fin.read( )
count=0
SOURCE for i in str:
CODE: if i=='a' or i=='e' or i=='i' or i=='o' or i=='u':
count=count+1
print(count)
OUTPUT: 9
6. Write a program to count number of words in a file.
fin=open("D:\\python programs\\Story.txt",'r')
str=fin.read( )
L=str.split()
SOURCE
CODE: count_words=0
for i in L:
count_words=count_words+1
print(count_words)
OUTPUT: 16
Write a program to count the number of times the occurrence of 'is' word in
7. a text file.
SOURCE fin=open("D:\\python programs\\Book.txt",'r')
CODE: str=fin.read( )
L=str.split( )
count=0
for i in L:
if i=='is':
count=count+1
print(count)
fin.close( )
OUTPUT: 3
file to another text file. Write a program to write those lines which have the
8.
character 'p' from one text
fin=open("E:\\book.txt","r")
fout=open("E:\\story.txt","a")
s=fin.readlines( )
for j in s:
SOURCE
CODE: if 'p' in j:
fout.write(j)
fin.close()
fout.close()
OUTPUT: **Write contents of book.txt and story.txt
Create a binary file with name and roll number of student and display the
9.
data by reading the file.
import pickle
def writedata( ):
list =[ ]
while True:
roll = input("Enter student Roll No:")
sname = input("Enter student Name :")
student = {"roll":roll,"name":sname}
list.append(student)
choice= input("Want to add more record(y/n) :")
if(choice=='n'):
break
SOURCE
CODE:
file = open("student.dat","wb")
pickle.dump(list,file)
file.close( )
def readdata( ):
file = open("student.dat", "rb")
list = pickle.load(file)
print(list)
file.close( )
print("Press-1 to write data and Press-2 to read data")
choice=int(input( ))
if choice==1:
writedata( )
elif choice==2:
readdata( )
else:
print("You entered invalid value")
Press-1 to write data and Press-2 to read data
1
Enter student Roll No:1201
Enter student Name :Devansh
Want to add more record(y/n) :y
OUTPUT: Enter student Roll No:1202
Enter student Name :Divya
Want to add more record(y/n) :n
Press-1 to write data and Press-2 to read data
2
[{'roll': '1201', 'name': 'Devansh'}, {'roll': '1202', 'name': 'Divya'}]
Write a program to search a record using its roll number and display the
10.
name of student. If record not found then display appropriate message.
import pickle
SOURCE
CODE: roll = input('Enter roll number that you want to search in binary file :')
file = open("student.dat", "rb")
list = pickle.load(file)
file.close( )
for x in list:
if roll in x['roll']:
print("Name of student is:", x['name'])
break
else:
print("Record not found")
OUTPUT:
Enter roll number that you want to search in binary file :1202
Name of student is: Divya
Write a program to update the name of student by using its roll number in a
11.
binary file.
import pickle
roll = input('Enter roll number whose name you want to update in binary file :')
file = open("student.dat", "rb+")
list = pickle.load(file)
found = 0
SOURCE
CODE:
lst = [ ]
for x in list:
if roll in x['roll']:
found = 1
x['name'] = input('Enter new name: ')
lst.append(x)
if found == 1:
file.seek(0)
pickle.dump(lst, file)
print("Record Updated")
else:
print('roll number does not exist')
file.close( )
Enter roll number whose name you want to update in binary file :1202
OUTPUT: Enter new name: Harish
Record Updated
12. Write a program to delete a record from binary file.
import pickle
roll = input('Enter roll number whose record you want to delete:')
file = open("student.dat", "rb+")
list = pickle.load(file)
found = 0
SOURCE
CODE:
lst = []
for x in list:
if roll not in x['roll']:
lst.append(x)
else:
found = 1
if found == 1:
file.seek(0)
pickle.dump(lst, file)
print("Record Deleted ")
else:
print('Roll Number does not exist')
file.close()
OUTPUT:
Enter roll number whose record you want to delete:1201
Record Deleted
13. Write a program to perform read and write operation with .csv file.
import csv
def readcsv():
with open('C:\\Users\\ViNi\\Downloads\\data.csv','rt')as f:
data = csv.reader(f) #reader function to generate a reader object
for row in data:
SOURCE
CODE: print(row)
def writecsv( ):
with open('C:\\Users\\ViNi\\Downloads\\data.csv', mode='a', newline='') as
file:
writer = csv.writer(file, delimiter=',', quotechar='"')
#write new record in file
writer.writerow(['4', 'Devansh', 'Arts', '404'])
print("Press-1 to Read Data and Press-2 to Write data: ")
a=int(input())
if a==1:
readcsv()
elif a==2:
writecsv()
else:
print("Invalid value")
Press-1 to Read Data and Press-2 to Write data:
['Roll No.', 'Name of student', 'stream', 'Marks']
['1', 'Anil', 'Arts', '426']
OUTPUT:
['2', 'Sujata', 'Science', '412']
['3', 'Shivani', 'Commerce', '448']
['4', 'Devansh', 'Arts', '404']
Write a program to generate random numbers between 1 to 6 and check
14. whether a user won a lottery or not.
import random
n=random.randint(1,6)
guess=int(input("Enter a number between 1 to 6 :"))
SOURCE if n==guess:
CODE: print("Congratulations, You won the lottery ")
else:
print("Sorry, Try again, The lucky number was : ", n)
Enter a number between 1 to 6 : 4
OUTPUT: Sorry, Try again, The lucky number was : 1
15. Write a program for linear search.
L=eval(input("Enter the elements: "))
n=len(L)
item=eval(input("Enter the element that you want to search : "))
for i in range(n):
SOURCE
CODE: if L[i]==item:
print("Element found at the position :", i+1)
break
else:
print("Element not Found")
Enter the elements: 23,67,44,99,65,33,78,12
OUTPUT: Enter the element that you want to search : 33
Element found at the position : 6
16. Write a menu based program to perform the operation on stack in python.
class Stack:
def init (self):
self.items = [ ]
def isEmpty(self): # Checks whether the stack is empty or not
return self.items == [ ]
def push(self, item): #Insert an element
self.items.append(item)
SOURCE
CODE: def pop(self): # Delete an element
return self.items.pop( )
def peek(self): #Check the value of top
return self.items[len(self.items)-1]
def size(self): # Size of the stack i.e. total no. of elements in
stack return len(self.items)
s = Stack( )
print("MENU BASED STACK")
cd=True
while cd:
print(" 1. Push ")
print(" 2. Pop ")
print(" 3. Display ")
print(" 4. Size of Stack ")
print(" 5. Value at Top ")
choice=int(input("Enter your choice (1-5) : "))
if choice==1:
val=input("Enter the element: ")
s.push(val)
elif choice==2:
if s.items==[ ]:
print("Stack is empty")
else:
print("Deleted element is :", s.pop( ))
elif choice==3:
print(s.items)
elif choice==4:
print("Size of the stack is :", s.size( ))
elif choice==5:
print("Value of top element is :", s.peek( ))
else:
print("You enetered wrong choice ")
print("Do you want to continue? Y/N")
option=input( )
if option=='y' or option=='Y':
var=True
else:
var=False
MENU BASED STACK
1. Push
2. Pop
3. Display
OUTPUT:
4. Size of Stack
5. Value at Top
Enter your choice (1-5) : 1
Enter the element: 45
Do you want to continue? Y/N
y
1. Push
2. Pop
3. Display
4. Size of Stack
5. Value at Top
Enter your choice (1-5) : 3
['45']
Do you want to continue? Y/N
y
1. Push
2. Pop
3. Display
4. Size of Stack
5. Value at Top
17. Predict the output of the following code.
def interest (prnc,time=2, rate=0.10):
return (prnc*time*rate)
Source code
print (interest(6100,1))
print (interest(5000,rate=0.05))
print (interest (5000,3,0.12))
print (interest(time=4,prnc=5000))
Output 610.0
500.0
1800.0
2000.0
18. Program that receives two numbers in a funcuntion and a reurns the results of all
arithmetic operations (+,-,*,/,%) on these numbers .
Source def arCalc(x,y):
Code return x+y , x-y , x*y , x/y , x%y
#__main__
Num1=int(input(“enter the number 1:”)
Num2=int(input(“enter the number 2:”)
Add,sub,mult,div,mod=arCalc (Num1,Num2)
print (“Sum of given numbers :”,add)
print (“Subtraction of given numbers :”,sub)
print (“Multiplication of given numbers :”,mult)
print (“Division of given numbers :”,div)
print (“Modulo of given numbers :”,mod)
Enter number 1: 13
Enter number 2: 7
Sum of given numbers :20
Output Subtraction of given numbers :6
Multiplication of given numbers:91
Division of given numbers:1.8571428571428572
Modulo of given numbers :6
19 Predict the output of following code.
Source code def state1 ( ):
tigers=15
print(tigers)
tigers =95
print(tigers)
state1()
print ( tigers)
Output 95
. 15
15
21. Create a table EMPLOYEE with constraints
SOLUTION
Step-1 Create a database:
CREATE DATABASE Bank;
Step-2 Display the databases
SHOW DATABASES;
Step-3: Enter into database
Use Bank;
Step-4: Create the table EMPLOYEE
create table Employee(Ecode int primary key,Ename varchar(20) NOT NULL,
Dept varchar(15),City varchar(15), sex char(1), DOB date, Salary float(12,2));
19. Insert data into the table
insert into Employee values(1001,"Atul","Production","Vadodara","M","1992-
10-23",23000.50);
SOLUTION Query OK, 1 row affected (0.11 sec)
Note: Insert more rows as per above insert command.
20. Add a new column in a table.
SOLUTION ALTER TABLE EMPLOYEE ADD address varchar(50);
21. Change the data-type and size of an existing column.
SOLUTION ALTER TABLE EMPLOYEE MODIFY city char(30);
Write SQL queries using SELECT, FROM, WHERE clause based on
22.
EMPLOYEE table.
1. List the name of female employees in EMPLOYEE table.
Solution:- SELECT Ename
FROM EMPLOYEE
WHERE sex=’F’;
2. Display the name and department of those employees who work in
surat and salary is greater than 25000.
Solution:- SELECT Ename, Dept
FROM EMPLOYEE
WHERE city=’surat’ and salary > 25000;
SOLUTION
3. Display the name of those female employees who work in
Mumbai. Solution:- SELECT Ename
FROM EMPLOYEE
WHERE sex=’F’ and city=’Mumbai’;
4. Display the name of those employees whose department is marketing or
RND.
Solution:- SELECT Ename
FROM EMPLOYEE
WHERE Dept=’marketing’ OR Dept=’RND’;
5. List the name of employe es who are not males.
Solution:- SELECT Ename, Sex
FROM EMPLOYEE
WHERE sex!=’M’;
Queries using DISTINCT, BETWEEN, IN, LIKE, IS NULL, ORDER BY,
23. GROUP BY, HAVING
A. Display the name of departments. Each department should be displayed once.
SELECT DISTINCT(Dept)
SOLUTION FROM EMPLOYEE;
Find the name and salary of those employees whose salary is between 35000
B.
and 40000.
SELECT Ename, salary
SOLUTION
FROM EMPLOYEE
WHERE salary BETWEEN 35000 and 40000;
C. Find the name of those employees who live in guwahati, surat or jaipur city.
SELECT Ename, city
SOLUTION FROM EMPLOYEE
WHERE city IN(‘Guwahati’,’Surat’,’Jaipur’);
D. Display the name of those employees whose name starts with ‘M’.
SELECT Ename
FROM EMPLOYEE
SOLUTION
WHERE Ename LIKE ‘M%’;
E. List the name of employees not assigned to any department.
SELECT Ename
SOLUTION FROM EMPLOYEE
WHERE Dept IS NULL;
F. Display the list of employees in descending order of employee code.
SELECT *
SOLUTION FROM EMPLOYEE
ORDER BY ecode DESC;
G. Find the average salary at each department.
SELECT Dept, avg(salary)
FROM EMPLOYEE
SOLUTION
group by Dept;
Find maximum salary of each department and display the name of that
H. department which has maximum salary more than 39000.
SELECT Dept, max(salary)
FROM EMPLOYEE
SOLUTION
group by Dept
HAVING max(salary)>39000;
24. Queries for Aggregate functions- SUM( ), AVG( ), MIN( ), MAX( ), COUNT( )
a. Find the average salary of the employees in employee table.
Solution:- SELECT avg(salary)
FROM EMPLOYEE;
b. Find the minimum salary of a female employee in EMPLOYEE table.
Solution:- SELECT Ename, min(salary)
FROM EMPLOYEE
WHERE sex=’F’;
c. Find the maximum salary of a male employee in EMPLOYEE table.
Solution:- SELECT Ename, max(salary)
FROM EMPLOYEE
WHERE sex=’M’;
d. Find the total salary of those employees who work in Guwahati city.
Solution:- SELECT sum(salary)
FROM EMPLOYEE
WHERE city=’Guwahati’;
e. Find the number of tuples in the EMPLOYEE relation.
Solution:- SELECT count(*)
FROM EMPLOYEE;
25. Write a program to connect Python with MySQL using database connectivity and
perform the following operations on data in database: Fetch, Update and delete
the data.
A. CREATE A TABLE
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
SOLUTION democursor=demodb.cursor( )
democursor.execute("CREATE TABLE STUDENT (admn_no int primary key,
sname varchar(30), gender char(1), DOB date, stream varchar(15), marks
float(4,2))")
B. INSERT THE DATA
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
SOLUTION passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("insert into student values (%s, %s, %s, %s, %s, %s)",
(1245, 'Arush', 'M', '2003-10-04', 'science', 67.34))
demodb.commit( )
C. FETCH THE DATA
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
SOLUTION
democursor.execute("select * from student")
for i in democursor:
print(i)
D. UPDATE THE RECORD
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
SOLUTION
passwd="computer", database="EDUCATION")
democursor=demodb.cursor( )
democursor.execute("update student set marks=55.68 where admn_no=1356")
demodb.commit( )
E. DELETE THE DATA
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
SOLUTION democursor=demodb.cursor( )
democursor.execute("delete from student where admn_no=1356")
demodb.commit( )