0% found this document useful (0 votes)
1 views

Practical_File_XII_CS

The document outlines the practical list and objectives for Class XII Computer Science at Kendriya Vidyalaya 14 GTC Subathu, detailing a minimum of 15 Python programs, 5 SQL queries, and 4 Python-SQL connectivity programs. It includes specific programming tasks such as checking for prime numbers, palindrome checks, and file operations, along with example codes and expected outputs. The document serves as a guide for students to complete their practical assignments in computer science.

Uploaded by

Saksham Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Practical_File_XII_CS

The document outlines the practical list and objectives for Class XII Computer Science at Kendriya Vidyalaya 14 GTC Subathu, detailing a minimum of 15 Python programs, 5 SQL queries, and 4 Python-SQL connectivity programs. It includes specific programming tasks such as checking for prime numbers, palindrome checks, and file operations, along with example codes and expected outputs. The document serves as a guide for students to complete their practical assignments in computer science.

Uploaded by

Saksham Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Kendriya Vidyalaya 14 GTC Subathu

Practical List with Programs of Computer Science (083), Class XII


Report file:
● Minimum 15 Python programs.
● SQL Queries – Minimum 5 sets using one table / two tables.
● Minimum 4 programs based on Python - SQL connectivity

S.N. Practical Details/Objective Date of


Practical
1. Write a program in python to check whether a number is prime
or not.
Python Code:
num=int(input("Enter the number: "))
isPrime = False
for i in range(2, num):
if num%i==0:
isPrime = False
break;
else:
isPrime = True
if isPrime == True:
print (num, "is a prime number.")
else:
print (num, "is not a prime number.")

Output:
2. Write a program to input a character and to print whether a
given character is an alphabet, digit or any other character.
Python Code:
ch=input("Enter a character: ")
if ch.isalpha():
print(ch, "is an alphabet")
elif ch.isdigit():
print(ch, "is a digit")
elif ch.isalnum():
print(ch, "is alphabet and numeric")
else:
print(ch, "is a special symbol")

Output:
3. Write a program to read a list of n integers (positive as well as
negative). Create two new lists, one having all positive numbers
and the other having all negative numbers from the given list.
Print all three lists.
Python Code:
L = list()
n=int(input('Enter number of elements to be appended in the
list:'))
for i in range(0,n):
ele = int(input('Elemnet: '))
L.append(ele)
pos_L=[]
neg_L=[]
for i in L:
1/15 Class XII CS Practical Lists – 2023-24, KV 14 GTC
Subathu
if i>=0:
pos_L.append(i)
else:
neg_L.append(i)
print('List with positive numbers:\n',pos_L)
print('List with negative numbers:\n',neg_L)

Output:
4. Write a function INDEX_LIST(L), where L is the list of elements
passed as argument to the function. The function returns
another list named ‘indexList’ that stores the indices of all Non-
Zero Elements of L.
For example: If L contains [12,4,0,11,0,56]
The indexList will have - [0,1,3,5]
Python Code:
def INDEX_LIST(L):
indexList=[]
for i in range(len(L)):
if L[i]!=0:
indexList.append(i)
return indexList

L= [12,4,0,11,0,56]
L1 = INDEX_LIST(L)
print('Returned list... \n',L1)

Output:
5. Write a function that takes a sentence as an input parameter
where each word in the sentence is separated by a space. The
function should replace each blank with a hyphen and then
return the modified sentence.
Python Code:
def textReplace(text):
new_str = text.replace(' ', '-')
return new_str
print('Text replacement...')
text=input('Enter a sentence: ')
new_Text= textReplace(text)
print('Modified string after text replacement...')
print(new_Text)

Output:
6. Write a program to check whether a number is palindrome or
not using function.
Python Code:
#Program to chek whether a number is pallindrome or not.
def isPallindrome(num):
res=0
while num>0:
rem=num%10
res=rem+res*10
num=num//10
return res

n = int(input("Enter a number: "))


2/15 Class XII CS Practical Lists – 2023-24, KV 14 GTC
Subathu
result = isPallindrome(n)
if result==n:
print("Number is Palindrome.")
else:
print("Number is not Palindrome.")

Output:
7. Write a function StuDetails( ) in python which accept a list of
marks of students and return the minimum mark, maximum
mark and the average marks.
Python Code:
def StuDetails(lst):
min_marks = min(lst)
max_marks = max(lst)
avg_marks = sum(lst)/len(lst)
return min_marks, max_marks, avg_marks

m_lst = []
print('Enter marks of 05 subject:')
for i in range(0, 5):
ele = int(input())
m_lst.append(ele)
min_marks, max_marks, avg_marks = StuDetails(m_lst)
print('Minimum marks: ',min_marks)
print('Maximum marks: ',max_marks)
print('Average marks: ',avg_marks)

Output:
8. Create a dictionary with the roll number, name and marks of n
students in a class and display the names of students who have
marks above 75.
Python Code:
n = int(input('Enter no. of records to be stored in the dictionary:
'))
d1 = {}
rec = 0
while n>0:
rec += 1
print('Record number',rec)
name = input('Enter student name: ')
marks = int(input('Enter student marks: '))
d1[name]=marks
n-=1

print('Name of students who secured marks above 75...')


for k in d1:
if d1[k]>75:
print('\t',k)

Output:
9. Write a function countNow(PLACES) in Python, that takes the
dictionary, PLACES as an argument and displays the count of
the names of the places whose names are longer than 5
characters.
For example, Consider the following dictionary
3/15 Class XII CS Practical Lists – 2023-24, KV 14 GTC
Subathu
PLACES={1:"Delhi",2:"London",3:"Paris",4:"Doha"}
The output should be:
Count of the places whose names are longer than 5 characters:
1
Python Code:
def countNOW(PLACES):
count = 0
for k,v in PLACES.items():
if len(v)>5:
count+=1
return count

PLACES={1:"Delhi",2:"London",3:"Paris",4:"Doha"}
count = countNOW(PLACES)
print("Count of the places whose names are longer than 5
characters:", count)

Output:

10. Write a Python program to create a text file and write your
name, class, roll, Father’s name, mother’s name and address in
it. (Using functions)
Python Code:

Output:
11. Read a text file and display the number of vowels/ consonants/
uppercase/ lowercase characters in the file. (Using functions)
Python Code:

Output:
12. Write a program to write those lines which have the character
'p' from one text file to another text file. (Using functions)
fin=open("Book.txt","r")
fout=open("Story.txt","a")
s=fin.readlines()
for j in s:
if 'p' in j:
fout.write(j)
fin.close()
fout.close()
print('Data Copied from Book.txt to Story.txt')
13. Write a program to accept a filename from the user and display
all the lines from the file which contain python comment
character '#'. (Using functions)
Python Code:

Output:
14. Write a function in Python that counts the number of “Me” or

4/15 Class XII CS Practical Lists – 2023-24, KV 14 GTC


Subathu
“My” words present in a text file “STORY.TXT”.
Python Code:

Output:
15. Write a program to write, read and display employee records in
a binary file. (Using functions)
Python Code:
# Program to write and read employee records in a binary file
import pickle
print("WORKING WITH BINARY FILES")
def writeRecords():
bfile=open("empfile.dat","ab")
recno=1
print ("Enter Records of Employees")
print()
#taking data from user and dumping in the file as list object
while True:
print("RECORD No.", recno)
eno=int(input("\tEmployee number : "))
ename=input("\tEmployee Name : ")
ebasic=int(input("\tBasic Salary : "))
allow=int(input("\tAllowances : "))
totsal=ebasic+allow
print("\tTOTAL SALARY : ", totsal)
edata=[eno,ename,ebasic,allow,totsal]
pickle.dump(edata,bfile)
ans=input("Do you wish to enter more records (y/n)? ")
recno=recno+1
if ans.lower()=='n':
print("Record entry OVER ")
print()
break
# retrieving the size of file
print("Size of binary file (in bytes):",bfile.tell())
bfile.close()

#Reading the employee records from the file using load()


module
def readRecords():
readrec=1
try:
with open("empfile.dat","rb") as bfile:
while True:
edata=pickle.load(bfile)
print("Record Number : ",readrec)
print(edata)
readrec=readrec+1
except EOFError:
pass
bfile.close()

writeRecords()
print("Now reading the employee records from the file")
5/15 Class XII CS Practical Lists – 2023-24, KV 14 GTC
Subathu
print()
readRecords()

Output:
16. Write a Python program to create a binary file with roll number,
name and marks. Input a roll number and update the marks.
(Using functions)
Python Code:
import pickle
def bfileCreate():
#Creating the dictionary
sd = {}
fout=open(r'Student16.dat','ab')
choice= input('Do you want to enter student details- Y/N?')
while choice in 'Yy' :
rollno = int(input('Enter roll number: '))
name = input('Enter Name: ')
marks = int(input('Enter Marks: '))
sd['Rollno'] = rollno
sd['Name']=name
sd['Marks']=marks
pickle.dump(sd,fout)
choice = input("Want to enter more data- Y / N: ")
if choice.upper() != 'Y':
break
fout.close()

def bfileDisplay():
fin= open(r'Student16.dat','rb')
try :
print('Students details............ ')
while True:
sd = pickle.load(fin)
print(sd)
except EOFError:
pass
fin.close()

def updateMarks(roll, nw_marks):


fin= open(r'Student16.dat','rb+')
try :
ch = 0
while True:
fp = fin.tell()
sd = pickle.load(fin)
if sd['Rollno']==roll:
sd['Marks'] = nw_marks
fin.seek(fp)
pickle.dump(sd,fin)
ch=1
print(sd)
except EOFError:
if ch ==1:
print('Student record updated.')
else:
6/15 Class XII CS Practical Lists – 2023-24, KV 14 GTC
Subathu
print('Student roll number not available!')
fin.close()

bfileCreate()
bfileDisplay()
print('Update student marks.......')
roll = int(input('Enter student roll number: '))
nw_marks = int(input('Enter marks for updation: '))
updateMarks(roll, nw_marks)

Output:
17. 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. (Using functions)
Python Code:
import pickle
def bfileCreate():
sd = {}
fout=open(r'Student17.dat','ab')
choice= input('Do you want to enter student details- Y/N?')
while choice in 'Yy' :
rollno = int(input('Enter roll number: '))
name = input('Enter Name: ')
sd['Rollno'] = rollno
sd['Name']=name
pickle.dump(sd,fout)
choice = input("Want to enter more data- Y / N: ")
if choice.upper() != 'Y':
break
fout.close()

def searchRoll(roll):
fin= open(r'Student17.dat','rb')
try :
ch = 0
while True:
sd = pickle.load(fin)
if sd['Rollno']==roll:
ch=1
print('Student details: \n',sd)
except EOFError:
if ch !=1:
print('Student roll number not found!')
fin.close()

bfileCreate()
print('Search Student Record....')
roll = int(input('Enter student roll number: '))
searchRoll(roll)
Output:
18. Write a program to perform read and write operation with a csv
file. (Using functions)
Python Code:
import csv
def readcsv():
7/15 Class XII CS Practical Lists – 2023-24, KV 14 GTC
Subathu
with open('data.csv','rt')as f:
data = csv.reader(f) #reader function to generate a
reader object
for row in data:
print(row)

def writecsv( ):
with open('data.csv', mode='a', newline='') as file:
writer = csv.writer(file, delimiter=',', quotechar='"')
#write new record in file
while True:
roll = input('Enter student roll: ')
name = input('Enter student name: ')
cls = input('Enter student class: ')
stream = input('Enter student stream: ')
writer.writerow([roll, name, cls, stream])
ans=input("Do you wish to enter more records (y/n)? ")
if ans.lower()=='n':
print("Record entry OVER ")
print()
break
print('Records in CSV file.....\n')
readcsv()

print('CSV file: ')


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

Output:
19. Create a CSV file by entering user-id and password, read and
search the password for given userid. (Using functions)
Python Code:

Output:
20. Write a menu based program to perform the operation on stack
in python using lists. (Using functions)
Python Code:
s=[]
def PUSH(a):
s.append(a)
def POP():
if (s==[]):
print( "Stack is empty.")
else:
print( "Deleted element is :", s.pop())
def DISP():
l=len(s)
8/15 Class XII CS Practical Lists – 2023-24, KV 14 GTC
Subathu
# To display elements from last element to first
if l!=0:
for i in range(l-1,-1,-1):
print(s[i])
else:
print('Stack is empty.')

ch="y"
while True:
print('Stack operations.....')
print( "1. PUSH" )
print( "2. POP" )
print( "3. Display")
choice=int(input("Enter your choice: "))
if (choice==1):
a=input("Push operation - Enter any number :")
PUSH(a)
elif (choice==2):
POP()
elif (choice==3):
DISP()
ch=input("Do you want to continue (y/n)?, N to exit ")
if ch in 'nN':
break

Output:

21. Julie has created a dictionary containing names and marks as


key value pairs of 6 students. Write a Python 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
Python Code:
R={"OM":76, "JAI":45, "BOB":89,"ALI":65, "ANU":90,
"TOM":82}
def PUSH(S, N):
S.append(N)

def POP(S):
if S!=[]:
return S.pop()
else:
return None

ST=[]
for k in R:
if R[k]>=75:
9/15 Class XII CS Practical Lists – 2023-24, KV 14 GTC
Subathu
PUSH(ST,k)

while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break

Output:
TOM ANU BOB OM
22. 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
Python Code:
N=[12, 13, 34, 56, 21, 79, 98, 22, 35, 38]
def PUSH(S,N):
S.append(N)

def POP(S):
if S!=[ ]:
return S.pop()
else:
return None

ST=[ ]
for k in N:
if k%2==0:
PUSH(ST,k)
while True:
el = POP(ST)
if el!= None:
print(el, end =' ')

Output:
38 22 98 56 34 12
23. Basic SQL Queries to Create Table
A. Write SQL query to create a database Organization
Quer CREATE DATABASE ORGANIZATION;
y
B. Write SQL query to show the lists of all databases.
Quer SHOW DATABASES;
y
C Write SQL query to select the Organization database.
Quer USE ORGANIZATION;
y
D Write SQL query to create Employee table with following
structure:
10/15 Class XII CS Practical Lists – 2023-24, KV 14 GTC
Subathu
ECODE INT PRIMARY KEY
ENAME VARCHAR(30) NOT NULL
DEPT VARCHAR(25)
SALARY INT
CITY VARCHAR(25)

Quer CREATE TABLE EMPLOYEE (ECODE INT PRIMARY KEY,


y ENAME VARCHAR(30) NOT NULL,
DEPT VARCHAR(25),
SALARY INT,
CITY VARCHAR(25));
E Write SQL query to show the lists of all tables of Organization
database.
Quer SHOW TABLES;
y
F Write SQL query to display the structure of table Employee.
Quer DESCRIBE EMPLOYEE;
y
G ECODE ENAME DEPT SALARY CITY
120 Alisha SALES 75000 GUWAHATI
123 Nitin NULL 59000
SUBATHU
129 Suman ACCOUNTS 40000
CHANDIGARH
130 Jefryy HR NULL NULL
131 Faizal HR 65000
NAHAN

Write SQL queries to insert the above mentioned data into


Employee Table.
Quer INSER INTO ……….
y
24. SQL Queries using Alter Table/ Update/ Delete
A Add a new column DATEOFJOINING with datatype as Date
into Employee table.
Quer ALTER TABLE EMPLOYEE ADD DATEOFJOINING DATE;
y
B Drop the column DATEOFJOINING from the table Employee.
Quer ALTER TABLE EMPLOYEE DROP DATEOFJOINING;
y
C Modify the SALARY of employee with ECODE as 130 from NULL
to 32000.
Quer UPDATE EMPLOYEE
y SET SALARY = 32000
WHERE ECODE = 130;
D Delete the record of employee having ECODE as 123.
Quer DELETE FROM EMPLOYEE
y WHERE ECODE = 123;
25. Select Queries using DISTINCT, BETWEEN, IN, LIKE, IS NULL,
ORDER BY, GROUP BY, HAVING Clauses
A Display the name of departments. Each department should be
displayed
once.
Quer SELECT DISTINCT(Dept)
y FROM EMPLOYEE;
11/15 Class XII CS Practical Lists – 2023-24, KV 14 GTC
Subathu
B Find the name and salary of those employees whose salary is
between 35000
and 40000.
Quer SELECT Ename, salary
y FROM EMPLOYEE
WHERE salary BETWEEN 35000 and 40000;
C Find the name of those employees who live in guwahati, surat or
jaipur city.
Quer SELECT Ename, city
y FROM EMPLOYEE
WHERE city IN(‘Guwahati’, ’Surat’, ’Jaipur’);
D Display the name of those employees whose name starts with
‘M’.
Quer SELECT Ename
y FROM EMPLOYEE
WHERE Ename LIKE ‘M%’;
E List the name of employees not assigned to any department.
Quer SELECT Ename
y FROM EMPLOYEE
WHERE Dept IS NULL;
F Display the list of employees in descending order of employee
code.
Quer SELECT *
y FROM EMPLOYEE
ORDER BY ecode DESC;
G Find the average salary of each department.
Quer SELECT Dept, avg(salary)
y FROM EMPLOYEE
GROUP BY Dept;
H Find the department wise total salary where total salary is
greater than 50000.
Quer SELECT Dept, SUM(salary)
y FROM EMPLOYEE
GROUP BY Dept
HAVING SUM(salary) > 50000;
26. SQL Queries for Aggregate functions- SUM( ), AVG( ), MIN( ),
MAX( ), COUNT( )
27. SQL Queries on Joins (Cartesian product on two tables, Equi-join
and natural join)
Table: Employee
EMPI NAM DOB DEPTI DESIG SALARY
D E D
120 Alisha 1978-01- D001 Manager 75000
23
123 Nitin 1977-10- D002 AO 59000
10
129 Navjo 1971-07- D003 Supervisor 40000
t 12
130 Jimmy 1980-12- D004 Sales Rep NULL
30
131 Faiz 1984-04- D001 Dep Manager 65000
06

Table: Department
12/15 Class XII CS Practical Lists – 2023-24, KV 14 GTC
Subathu
DEPTID DEPTNAME FLOORNO
D001 Personal 4 4
D002 Admin 10 10
D003 Production 1
D004 Sales 3 3

Consider the above mentioned tables and write following


queries based on these tables:
A To display name and respective department name of each
employee
whose salary is NULL.
Quer SELECT NAME, DEPTNAME
y FROM EMPLOYEE, DEPARTMENT
WHERE EMPLOYEE.DEPTID= DEPARTMENT.DEPTID
AND SALARY IS NULL;
B To display name and respective department name of each
employee
whose salary is more than 50000.
Quer SELECT NAME, DEPTNAME
y FROM EMPLOYEE, DEPARTMENT
WHERE EMPLOYEE.DEPTID= DEPARTMENT.DEPTID
AND SALARY>50000;
C To display the names of employees along with department
names whose
salary is not known, in alphabetical order of name.
Quer SELECT NAME, DEPTNAME
y FROM EMPLOYEE, DEPARTMENT
WHERE EMPLOYEE.DEPTID= DEPARTMENT.DEPTID
AND SALARY IS NULL
ORDER BY NAME;
D To count the number of employees of Personal department along
with
department name.
Quer SELECT DEPTNAME, COUNT(*)
y FROM EMPLOYEE, DEPARTMENT
WHERE EMPLOYEE.DEPTID= DEPARTMENT.DEPTID
AND DEPARTMENT = ‘PERSONAL’;
E To display name, designation and respective department name
of each
employee
Quer SELECT NAME, DESIG, DEPTNAME
y FROM EMPLOYEE, DEPARTMENT
WHERE EMPLOYEE.DEPTID= DEPARTMENT.DEPTID;
F Write SQL query with output to apply NATURAL JOIN on
EMPLOYEE and DEPARTMENT table.
Quer
y
G Write SQL query with output to apply EQUI JOIN on EMPLOYEE
and DEPARTMENT table.
Quer
y
Write following programs (28 to 34) to connect Python with
MySQL using database connectivity and perform the following
operations on data in database:

13/15 Class XII CS Practical Lists – 2023-24, KV 14 GTC


Subathu
28. Create a Database and table.
Python Code:
import mysql.connector as sql
myCon = sql.connect(host='localhost', user='root',
passwd='tiger')
cr = myCon.cursor()
cmd='create database MyRestaurant;'
cr.execute(cmd)
cmd1 ='show databases;'
cr.execute(cmd1)
print(cr.fetchall( ))

Output:

29. CREATE A TABLE


Python Code:
import mysql.connector as sql
myCon = sql.connect(host='localhost', user='root',
passwd='tiger',
database='MyRestaurant')
cr = myCon.cursor()
cmd = 'create table menu(itemno int primary key, name
varchar(20), price
int);'
cmd1 = 'Show tables;'
cr.execute(cmd)
print('Table created successfully.')
cr.execute(cmd1)
print('List of tables in MyRestaurant Database:')
print(cr.fetchall())

Output:

30. Insert data into the already created table.


Python Code:
import mysql.connector as sql
myCon = sql.connect(host='localhost', user='root',
passwd='tiger', database='MyRestaurant')
cr = myCon.cursor()
count = int(input('Please enter the number of item details to be
added: '))
for i in range(count):
ino = int(input("Enter item no.: "))
iname = input("Enter item name: ")
iprice = int(input("Enter item price: "))
#cmd6 = 'insert into menu values({0},"{1}",{2})'.format(ino,
iname, iprice)
cmd7 = 'insert into menuvalues({no}, "{name}",
{price} )'.format(no=ino, name=iname, price=iprice)
cr.execute(cmd7)
print('----Item details added.----')
myCon.commit()

Output:

14/15 Class XII CS Practical Lists – 2023-24, KV 14 GTC


Subathu
31. Fetch data from the table.
Python Code:
import mysql.connector as sql
myCon = sql.connect(host='localhost', user='root',
passwd='tiger',
database='MyRestaurant')
cr = myCon.cursor()
cmd = 'SELECT * FROM MENU;'
cr.execute(cmd)
print('Details of items: ')
for i in cr:
print(i)

Output:

32. Update data according to user needs.


Python Code:

Output:

33. Delete data according to user needs.


34. Python Code:

Output:

15/15 Class XII CS Practical Lists – 2023-24, KV 14 GTC


Subathu

You might also like