Cs Prac Xii 25-26
Cs Prac Xii 25-26
KONI, BILASPUR
Practical record
Subject: (083) Computer Science
Session: 2025-26
CERTIFICATE
This is to certify that ……GOPAL..YADAV.………. of XII ……. of Krishna Public School,
Koni, Bilaspur, has completed his/her practical file under my supervision. He/She has
completed the practical work independently and has shown utmost sincerity in
completion of this file. This practical file fully implements all the topics and concepts
learnt in
1. Python
2. Data File Handling
3. MySql
4. Networking Concepts
covered in class XI and XII as per the C.B.S.E syllabus of Computer Science Subject, I
certify that this practical file is up to my expectations and as per guidelines issued by
C.B.S.E.
Signature Signature
Sujeet Tiwari _________________________________
(PGT Computer Science) External Examiner
Signature
Mrs. Runki Ambastha
(PRINCIPAL)
9 Remove all the lines that contain the character 'a' in a file and
write it to another file.
11 Write a Python function that finds and displays all the words
longer than 5 characters from a text file "Words.txt".
Binary File
12 Create a binary file with name and roll number. …
13 Create a binary file with roll number, name and marks. Input a
roll number and update the marks.
CSV File
Module
19 Write a random number generator that generates random
numbers between 1 and 6 (simulates a dice).
Stack
20 Write a Python program to implement a stack using list.
Database Management
24 • Data base and Table Creation
• 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
• UPDATE table to modify data
• ORDER By to display data in ascending / descending
order
• DELETE to remove tuple(s)
• GROUP BY and find the min, max, sum, count and
average
SQL Joins
25 Equi join
Python SQL Connectivity
Output:
Practical: -2
WAP to create UDF and call with Labelled Argument
Program:
#just Call the above function with variable name
#calling a function
myFunction(b=10, a=20,c=30)
Output:
Practical: -3
WAP to create UDF and call function with arbitrary argument
Program:
#function definition
def myFunction(*a):
c=0
for i in a:
c+=1
print("argument ",c,":",i)
#function calling
myFunction(10,20,"Hello",[1,2,3,4])
Output:
Practical: -4
Write a function countNow(PLACES) in Python, that takes the dictionary, PLACES as
an argument and displays the names (in uppercase)of the places whose names are
longer than 5 characters.
For example,
Consider the following dictionary PLACES={1:"Delhi",2:"London",3:"Paris",4:"New
York",5:"Doha"}
The output should be: LONDON NEW YORK
Program:
#function name should be countNow and argument must be PLACES
def countNow(PLACES): #1/2
for i in PLACES: #1/2
if len(PLACES[i])>5: #1/2
print(PLACES[i].upper()) #1/2
#calling a function
PLACES={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Doha"}
countNow(PLACES) #1/2
Output:
Practical: -5
Write a function, lenWords(STRING), that takes a string as an argument and returns
a tuple containing length of each word of a string.
For example, if the string is "Come let us have some fun",
the tuple will have (4, 3, 2, 4, 4, 3)
Program:
#function name should be lenWords and argument must be STRING
def lenWords(STRING):
#adding each individual word as object into list
l=STRING.split()
#Empty list to store count of each word
countList=[]
for i in l:
countList.append(len(i))
#converting list into tuple and return back
return tuple(countList)
#calling function'
STRING="Come let us have some fun"
result=lenWords(STRING)
print("input text:",STRING)
print("Return result:",result)
Output:
Practical: -6
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]
Program:
#function name should be INDEX_LIST and argument must be L
def INDEX_LIST(L):
#empty list to store index of non zero element
indexList=[]
for i in L:
if i>0:
indexList.append(L.index(i))
return indexList
#calling function
L=[12,4,0,11,0,56]
indexList=INDEX_LIST(L)
print("List Passed:",L)
print("Result Received:",indexList)
Output:
Practical: -7
Read a text file line by line and display each word separated by a #.
Program:
#open a file in read mode
file=open("sample.txt",mode="r")
#read entire file
data=file.read()
#replace blank space with #
data=data.replace(" ","#")
#print result
print(data)
#close connection
file.close()
Output:
Practical: -8
Read a text file and display the number of vowels/consonants/uppercase/lowercase characters in the file.
Program:
#open text file
file=open("sample.txt",mode="r")
#read entire file
data=file.read()
#counting variables
vowelCount=0
consonentCount=0
upperCount=0
lowerCount=0
for i in data:
if i in "aeiouAEIOU":
vowelCount+=1
elif i.isalpha():
consonentCount+=1
if i.isupper():
upperCount+=1
elif i.islower():
lowerCount+=1
print("Total Vovel:",vowelCount)
print("Total Consonent:",consonentCount)
print("Total Upper:",upperCount)
print("Total Lower:",lowerCount)
file.close()
Output:
Practical: -9
Remove all the lines that contain the character 'a' in a file and write it to another file.
Program:
#open a file in read mode
file=open("sample.txt",mode="r")
out=open("output.txt","w")
#read entire file
data=file.readlines()
#check for char 'a' and remove line
for i in data:
if 'a' not in i:
out.writelines(i)
#close connection
file.close()
out.close()
Output:
Sample.txt Output.txt
Lorem Ipsum is simply dummy text of the printing and this line is without the
typesetting industry. specieied object which we need
this line is without the specieied object which we need to to remove
remove
Lorem Ipsum has been the industry's standard dummy text ever
since the 1500s,
when an unknown printer took a galley of type and scrambled it
to make a type specimen book.
It has survived not only five centuries, but also the leap into
electronic typesetting, remaining essentially unchanged.
It was popularised in the 1960s with the release of Letraset
sheets containing Lorem Ipsum passages,
and more recently with desktop publishing software like Aldus
PageMaker including versions of Lorem Ipsum.
Practical: -10
Write a Python function that displays all the words containing @cmail from a text file "Emails.txt".
Program
def show():
f=open("Email.txt",'r')
data=f.read()
words=data.split()
for word in words:
if '@cmail' in word:
print(word,end=' ')
f.close()
Output:
admin@cmail user@cmail
Sample Text File:
admin@cmail admin@gmail mohan@ymail user@cmail
Expected Output:
admin@cmail user@cmail
Practical: -11
Write a Python function that finds and displays all the words longer than 5 characters from a text file
"Words.txt".
Program
def display_long_words():
with open("Words.txt", 'r') as file:
data=file.read()
words=data.split()
for word in words:
if len(word)>5:
print(word,end=' ')
Output
Text in file:
A quick brown fox jumps over the lazy dog
Output:
quick brown jumps
Practical: -12
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.
Program:
#open a binary file in write+read mode mode
import pickle
file=open("student.dat",mode="wb")
#store student data
data=[[101,"Mohan"],[102,"Sohan"],[103,"Sita"],[104,"Geeta"]]
pickle.dump(data,file)
file.close()
Program:
import pickle
file=open("student.dat",mode="wb")
#store student data
data=[[101,"Mohan",0],[102,"Sohan",0],[103,"Sita",0],[104,"Geeta",0]]
pickle.dump(data,file)
file.close()
#open file to read
file=open("student.dat",mode="rb")
#Read and modify data
result=pickle.load(file)
print(result)
roll=int(input("Enter roll number:"))
count=0
for i in range(len(result)):
print(result[i])
if roll == result[i][0]:
print("Name:",result[i][1])
m=int(input("Enter Marks:"))
result[i][2]=m
count+=1
break
if count==0:
print("No record found")
file.close()
file=open("student.dat",mode="wb")
#store student data
pickle.dump(result,file)
file.close()
#Checking the modification
file=open("student.dat",mode="rb")
#store student data
result=pickle.load(file)
print(result)
file.close()
Output:
#When roll number exist
- Candidate_ID – integer
- Candidate_Name – string
- Designation – string
- Experience – float
You, as a programmer of the company, have been assigned to do this job for Surya
(1) Write a function to input the data of a candidate and append it in a binary file.
(2) Write a function to update the data of candidates whose experience is more than 10 years and
change their designation to "Senior Manager".
(3) Write a function to read the data from the binary file and display the data of all those candidates
who are not "Senior Manager".
Program
import pickle
#Function-1
def input_candidates():
candidates = []
n = int(input("Enter the number of candidates you want to add: "))
for i in range(n):
candidate_id = int(input("Enter Candidate ID: "))
candidate_name = input("Enter Candidate Name: ")
designation = input("Enter Designation: ")
experience = float(input("Enter Experience (in years): "))
candidates.append([candidate_id, candidate_name, designation,
experience])
return candidates
#calling the above function
candidates_list = input_candidates()
#Function-2
def append_candidate_data(candidates):
with open('candidates.bin', 'ab') as file:
for candidate in candidates:
pickle.dump(candidate, file)
print("Candidate data appended successfully.")
#calling the function
append_candidate_data(candidates_list)
#Function-3
def update_senior_manager():
updated_candidates = []
try:
with open('candidates.bin', 'rb') as file:
while True:
try:
candidate = pickle.load(file)
if candidate[3] > 10: # If experience > 10years
candidate[2] = 'Senior Manager'
updated_candidates.append(candidate)
except EOFError:
break # End of file reached
except FileNotFoundError:
print("No candidate data found. Please add candidates
first.")
return
#calling function
with open('candidates.bin', 'wb') as file:
for candidate in updated_candidates:
pickle.dump(candidate, file)
print("Candidates updated to Senior Manager where applicable.")
update_senior_manager()
#Function-4
display_non_senior_managers():
try: with open('candidates.bin', 'rb') as file:
while True:
try:
candidate = pickle.load(file)
if candidate[2] != 'Senior Manager':
# Check if not Senior Manager
print(f"Candidate ID: {candidate[0]}")
print(f"Candidate Name: {candidate[1]}")
print(f"Designation: {candidate[2]}")
print(f"Experience: {candidate[3]}")
print("--------------------")
except EOFError:
break
# End of file reached
except FileNotFoundError:
print("No candidate data found. Please add candidates
first.")
#Calling the function
display_non_senior_managers()
Practical: -15
Create a CSV file by entering user-id and password, read and search the password for given userid.
Program:
#part-1 Create file and store record
import csv
#open csv file to write username and password
file=open("userdata.csv","w+",newline="")
writer=csv.writer(file)
#input from user
uid=input("Enter User Name:")
pwd=input("Enter Password:")
data=[uid,pwd]
writer.writerow(data)
file.close()
Program:
def copyData():
file1=open("sport.dat","rb")
file2=open("basket.dat","wb")
cnt=0
try:
while True:
data=pickle.load(file)
print(data)
if data[0]=="Basket Ball":
pickle.dump(data,file2)
except:
file.close()
file2.close()
return cnt
Practical: -17
Write a method COUNTLINES() in Python to read lines from text file ‘TESTFILE.TXT’ and display the lines which
are not starting with any vowel.
Example: If the file content is as follows: An apple a day keeps the doctor away. We all pray for everyone’s
safety. A marked difference will come in our country.
Output:
File content:
Testfile.txt:
An apple a day keeps the doctor away.
We all pray for everyone’s safety.
A marked difference will come in our country.
Result
Practical: -18
A csv file "Happiness.csv" contains the data of a survey. Each record of the file contains the following data:
● Name of a country
● Population of the country
● Sample Size (Number of persons who participated in the survey in that country)
● Happy (Number of persons who accepted that they were Happy)
For example, a sample record of the file may be: [‘Signiland’, 5673000, 5000, 3426]
Write the following Python functions to perform the specified operations on this file:
(I) Read all the data from the file in the form of a list and display all those records for which the
population is more than 5000000.
(II) Count the number of records in the file.
Program
def show():
import csv
f=open("happiness.csv",'r')
records=csv.reader(f)
next(records, None) #To skip the Header row
for i in records:
if int(i[1])>5000000:
print(i)
f.close()
Count_records():
f=open("happiness.csv",'r')
records=csv.reader(f)
next(records, None) #To skip the Header row
count=0
for i in records:
count+=1
print(count)
f.close()
Practical: -19
Write a random number generator that generates random numbers between 1 and 6 (simulates a dice).
Program:
import random
while True:
n=random.randint(1,6)
print(n)
ch=input("Do you want to continue:y/n")
if ch in 'yY':
pass
else:
break
Output:
Practical: -20
Write a Python program to implement a stack using list.
Program:
stack=[]
max=5
def pushData(data):
if len(stack)<max:
stack.append(data)
print("Data Inserted successfully..")
else:
print("Stack is full")
def popData():
if len(stack)>0:
data=stack.pop()
return data
else:
print("Stack is empty")
return -1
pushData(5)
pushData(10)
pushData(3)
pushData(9)
pushData(20)
pushData(25)
print(popData())
print(popData())
print(popData())
print(popData())
print(popData())
print(popData())
Output:
Practical: -21
A list, NList contains following record as list elements:
Write the following user defined functions in Python to perform the specified operations on the stack named
travel.
(i) Push_element(NList): It takes the nested list as an argument and pushes a list object containing name of the
city and country, which are not in India and distance is less than 3500 km from Delhi.
(ii) Pop_element(): It pops the objects from the stack and displays them. Also, the function should display
“Stack Empty” when there are no elements in the stack.
Program:
travel=[]
def Push_element(Nlist):
for l in Nlist:
if l[1]!="India" and l[2]<3500:
travel.append([l[0],l[1]])
def Pop_element():
while len(travel):
print(travel.pop())
else:
print("Stack Empty")
data=[
["1","2",4500],
["2","2",2500],
["3","India",2500]]
Push_element(data)
Pop_element()
Output:
Practical: -22
You have a stack named BooksStack that contains records of books. Each book record is represented as a list
containing book_title, author_name, and publication_year.
Write the following user-defined functions in Python to perform the specified operations on the stack
BooksStack:
(I) push_book(BooksStack, new_book): This function takes the stack BooksStack and a new book record
new_book as arguments and pushes the new book record onto the stack.
(II) pop_book(BooksStack): This function pops the topmost book record from the stack and returns it. If the
stack is already empty, the function should display "Underflow".
(III) peep(BookStack): This function displays the topmost element of the stack without deleting it. If the stack is
empty, the function should display 'None'
Program
def push_book(BooksStack, new_book):
BooksStack.append(new_book)
def pop_book(BooksStack):
if not BooksStack:
print("Underflow")
else:
return(BookStack.pop())
def peep(BooksStack):
if not BooksStack:
print("None")
else:
print(BookStack[-1])
Practical: -23
Write the definition of a user-defined function `push_even(N)` which accepts a list of integers in a parameter `N`
and pushes all those integers which are even from the list `N` into a Stack named `EvenNumbers`.
Write function pop_even() to pop the topmost number from the stack and returns it. If the stack is already
empty, the function should display "Empty".
Write function Disp_even() to display all element of the stack without deleting them. If the stack is empty, the
function should display 'None'.
For example:
If the integers input into the list `VALUES` are: [10, 5, 8, 3, 12]
Then the stack `EvenNumbers` should store: [10, 8, 12]
Program
def push_even(N):
EvenNumbers = []
for num in N:
if num % 2 == 0:
EvenNumbers.append(num)
return EvenNumbers
VALUES = []
for i in range(5):
VALUES.append(int(input("Enter an integer: ")))
EvenNumbers = push_even(VALUES)
def pop_even():
if not EvenNumbers:
print("Underflow")
else:
print(EvenNumbers.pop())
pop_even()
def Disp_even():
if not EvenNumbers:
print("None")
else: print(EvenNumbers[-1])
Disp_even()
DATABASE Using MYSQL
Practical: -24
Create Data base:
Syntax: create database databasename;
Query: create database stdinfo;
Terminal View:
Use database:
Syntax: use databasename;
Query: use stdinfo;
Terminal View:
Show List of Tables:
Syntax: show tables;
Query: Show tables;
Terminal View:
Create New Table:
Syntax:
Create Table tablename
( col1 datatype constrains,
Col2 datatype constrains, ..);
The following constraints are commonly used in SQL:
• NOT NULL - Ensures that a column cannot have a NULL value
• UNIQUE - Ensures that all values in a column are different
• PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies
each row in a table
• FOREIGN KEY - Prevents actions that would destroy links between tables
• CHECK - Ensures that the values in a column satisfies a specific condition
• DEFAULT - Sets a default value for a column if no value is specified
• CREATE INDEX - Used to create and retrieve data from the database very
quickly
Query:
1. insert into student (rollno,stdname,class,section) values
(101,"Mohan","XII","A");
2. insert into student values(102,"Sita","XII","A");
3. insert into student values (103,"Ramesh","XI","A"),
(104,"Rakesh","XI","A"),(105,"Rita","XII","A");
Terminal View:
1. Adding singal data using label of column
Terminal View:
Terminal View:
Change name of any column
Syntax: ALTER TABLE table_name
RENAME COLUMN old_name to new_name;
Terminal View:
Terminal View:
Change constrains of table
Syntax: ALTER TABLE Persons
modify COLUMN column_name datatype constrains;
Terminal View:
Aggregator functions
Distinct()
Query: select distinct(class) from student;
Terminal View:
Sum()
Query: select sum(rollno) from student;
Terminal View:
Avg()
Query: select avg(rollno) from student;
Terminal View:
Count()
Query: select avg(rollno) from student;
Terminal View:
Max()
Query: select max(rollno) from student;
Terminal View:
Min()
Query: select min(rollno) from student;
Terminal View:
Practical: -25
SQL JOINS
Equi join
Query: Select * from student, marks where
student.rollno=marks.rollno;
Terminal:
Practical: -26
Integrate SQL with Python by importing suitable module.
Program:
#python sql
#step 1 import connector
import mysql.connector
db.close()
Output: