CBSE+2: Python Practical Programs
CBSE+2 -Practical File
Python Programming
● Read a text file line by line and display each word separated by a #.
● Read a text file and display the number of vowels/consonants/uppercase/lowercase
characters in the file.
● Remove all the lines that contain the character 'a' in a file and write it to another file.
● 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.
● Create a binary file with roll number, name and marks. Input a roll number and update
the marks.
● Write a random number generator that generates random numbers between 1 and 6
(simulates a dice).
● Write a Python program to implement a stack using list.
● Create a CSV file by entering user-id and password, read and search the password for
given user id
Database Management
● Create a student table and insert data. Implement the following SQL commands on the
student table:
o ALTER table to add new attributes / modify data type / drop attribute
o UPDATE table to modify data
o ORDER By to display data in ascending / descending order
o DELETE to remove tuple(s)
o GROUP BY and find the min, max, sum, count and average
● Similar exercise may be framed for other cases.
● Integrate SQL with Python by importing suitable module.
Note:
Dear Students please follow the instructions
while writing records
➢ Question must be written on rules side.
➢ Python program must be written on rule side (ruled page).
➢ Similarly, SQL commands must be written on rule side
(ruled line)
➢ Output should be written in left side un ruled (white page)
in pencil. all the output are in box (SQL table)
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 1
CBSE+2: Python Practical Programs
1. # Practical prog-1 Read a text file line by line and display each word
separated by a'#'
def word_as():
file=open("C:\\Users\\ranga\\Desktop\\fhandle\\test.txt","r")
lines=file.readline()
for line in lines:
words=line.split()
for word in words:
print(word+"#",end=" ")
print(" ")
file.close()
#main program
word_as()
Output
I# d# r#
n# o#
d# a# t#
i# l# h#
a# l# e#
r#
i# I# s#
s# n#
d# a#
m# i# n#
y# a# d#
n#
c# s# s#
o# i#
u# a# s#
n# r# t#
t# e# e#
r# r#
y# m# s#
y# .#
a#
n# b#
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 2
CBSE+2: Python Practical Programs
2. Read a text file and display the number of vowels/ consonants/
uppercase/ lowercase characters in the file.
def cnt():
f=open("C:\\Users\\ranga\\Desktop\\fhandle\\test.txt","r")
cont=f.read()
print(cnt)
v=0
cons=0
l_c_l=0
u_c_l=0
for ch in cont:
if (ch.islower()):
l_c_l+=1
elif(ch.isupper()):
u_c_l+=1
ch=ch.lower()
if( ch in ['a','e','i','o','u']):
v+=1
elif (ch in ['b','c','d','f','g',
'h','j','k','l','m',
'n','p','q','r','s',
't','v','w','x','y','z']):
cons+=1
f.close()
print("Vowels are : ",v)
print("consonants are : ",cons)
print("Lower case letters are : ",l_c_l)
print("Upper case letters are : ",u_c_l)
#main program
cnt()
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 3
CBSE+2: Python Practical Programs
Output:
<function cnt at 0x000001DE0765C0D0>
Vowels are : 18
consonants are : 34
Lower case letters are : 50
Upper case letters are : 2
3. #Practical Program 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.
import pickle
import sys
dict={}
def write_in_file():
file=open("C:\\Users\\ranga\\Desktop\\fhandle\\stud.dat","ab") #a-
append,b-binary
no=int(input("ENTER NO OF STUDENTS: "))
for i in range(no):
print("Enter details of student ", i+1)
dict["roll"]=int(input("Enter roll number: "))
dict["name"]=input("enter the name: ")
pickle.dump(dict,file) #dump-to write in student file
file.close()
def display():
#read from file and display
file=open("C:\\Users\\ranga\\Desktop\\fhandle\\stud.dat","rb") #r-
read,b-binary
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 4
CBSE+2: Python Practical Programs
try:
while True:
stud=pickle.load(file) #write to the file
print(stud)
except EOFError:
pass
file.close()
def search():
file=open("C:\\Users\\ranga\\Desktop\\fhandle\\stud.dat","rb") #r-
read,b-binary
r=int(input("Enter the rollno to search: "))
found=0
try:
while True:
data=pickle.load(file) #read from file
if data["roll"]==r:
print("The rollno =",r," record found")
print(data)
found=1
break
except EOFError:
pass
if found==0:
print("The rollno =",r," record is not found")
file.close()
#main program
#Prepared by Ramesha K S
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 5
CBSE+2: Python Practical Programs
while True:
print("MENU \n 1-Write in a file \n 2-display ")
print(" 3-search\n 4-exit \n")
ch=int(input("Enter your choice = "))
if ch==1:
write_in_file()
if ch==2:
display()
if ch==3:
search()
if ch==4:
print(" Thank you ")
sys.exit()
Output:
MENU
1-Write in a file
2-display
3-search
4-exit
Enter your choice = 1
ENTER NO OF STUDENTS: 3
Enter details of student 1
Enter roll number: 101
enter the name: Ranganath
Enter details of student 2
Enter roll number: 102
enter the name: Madhusudan
Enter details of student 3
Enter roll number: 103
enter the name: Kiran
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 6
CBSE+2: Python Practical Programs
MENU
1-Write in a file
2-display
3-search
4-exit
Enter your choice = 2
{'roll': 101, 'name': 'Ranganath'}
{'roll': 102, 'name': 'Madhusudan'}
{'roll': 103, 'name': 'Kiran'}
MENU
1-Write in a file
2-display
3-search
4-exit
Enter your choice = 3
Enter the rollno to search: 101
The rollno = 101 record found
{'roll': 101, 'name': 'Ranganath'}
MENU
1-Write in a file
2-display
3-search
4-exit
Enter your choice =
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 7
CBSE+2: Python Practical Programs
4. Create a binary file with roll number, name and marks. Input a roll
number and update the marks.
import pickle
student_data={}
no_of_students=int(input("Enter no of students: "))
file=open("student0.dat","ab")
for i in range(no_of_students):
student_data["RollNo"]=int(input("Enter roll no: "))
student_data["Name"]=input("Enter Student name: ")
student_data["Marks"]=float(input("Enter Student Marks: "))
pickle.dump(student_data,file)
student_data={}
file.close()
file=open("student0.dat","rb")
try:
while True:
student_data=pickle.load(file)
print(student_data)
except EOFError:
file.close()
found=False
roll_no=int(input("enter the roll no to search: "))
file=open("student0.dat","rb+")
try:
while True:
pos=file.tell()
student_data=pickle.load(file)
if(student_data["RollNo"])==roll_no:
student_data["Marks"]=float(input("Enter marks to be updated: "))
file.seek(pos)
pickle.dump(student_data,file)
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 8
CBSE+2: Python Practical Programs
found=True
except EOFError:
if(found==False):
print("Roll no not found Please Try Again")
else:
print("Student marks updated successfully")
file.close()
file=open("student0.dat","rb")
try:
while True:
student_data=pickle.load(file)
print(student_data)
except EOFError:
file.close()
file=open("student0.dat","rb")
try:
while True:
student_data=pickle.load(file)
print(student_data)
except EOFError:
file.close()
Output
Enter no of students: 3
Enter roll no: 101
Enter Student name: VINAY
Enter Student Marks: 550
Enter roll no: 102
Enter Student name: SAANVI
Enter Student Marks: 580
Enter roll no: 103
Enter Student name: SUDHA
Enter Student Marks: 450
{'RollNo': 101, 'Name': 'VINAY', 'Marks': 550.0}
{'RollNo': 102, 'Name': 'SAANVI', 'Marks': 580.0}
{'RollNo': 103, 'Name': 'SUDHA', 'Marks': 450.0}
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 9
CBSE+2: Python Practical Programs
enter the roll no to search: 102
Enter marks to be updated: 590
Student marks updated successfully
{'RollNo': 101, 'Name': 'VINAY', 'Marks': 550.0}
{'RollNo': 102, 'Name': 'SAANVI', 'Marks': 590.0}
{'RollNo': 103, 'Name': 'SUDHA', 'Marks': 450.0}
{'RollNo': 101, 'Name': 'VINAY', 'Marks': 550.0}
{'RollNo': 102, 'Name': 'SAANVI', 'Marks': 590.0}
{'RollNo': 103, 'Name': 'SUDHA', 'Marks': 450.0}
>>>
5. Remove all the lines that contain the character `a' in a file and write it to
another file.
fin=open("C:\\Users\\ranga\\Desktop\\fhandle\\book.txt","r")
fout=open("C:\\Users\\ranga\\Desktop\\fhandle\\book.txt","w")
s=fin.readlines()
for j in s:
if 'a' in j:
fout.write(j)
fout.close()
fin.close()
6. Write a random number generator that generates random numbers
between 1 and 6 (simulates a dice).
def random():
import random
s=random.randint(1,6)
return s
print(random())
Ouput
5
4
3
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 10
CBSE+2: Python Practical Programs
7. Write a Python program to implement a stack and queue using a list data
structure
def isEmpty(stk): # checks whether the stack is empty or not
if stk==[]:
return True
else:
return False
def Push(stk,item): # Allow additions to the stack
stk.append(item)
top=len(stk)-1
def Pop(stk):
if isEmpty(stk): # verifies whether the stack is empty or not
print("Underflow")
else: # Allow deletions from the stack
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)
print("Popped item is "+str(item))
def Display(stk):
if isEmpty(stk):
print("Stack is empty")
else:
top=len(stk)-1
print("Elements in the stack are: ")
for i in range(top,-1,-1):
print (str(stk[i]))
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 11
CBSE+2: Python Practical Programs
# executable code
if __name__ == "__main__":
stk=[]
top=None
Push(stk,10)
Push(stk,20)
Push(stk,30)
Push(stk,40)
Pop(stk)
Display(stk)
Output:
Popped item is 40
Elements in the stack are:
30
20
10
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 12
CBSE+2: Python Practical Programs
8. Take a sample of ten phishing e-mails (or any text file) and find most
commonly occurring word(s).
#Text file is must
def Read_Email_File():
import collections
fin = open('email.txt','r')
a= fin.read()
d={ }
L=a.lower().split()
for word in L:
word = word.replace(".","")
word = word.replace(",","")
word = word.replace(":","")
word = word.replace("\"","")
word = word.replace("!","")
word = word.replace("&","")
word = word.replace("*","")
for k in L:
key=k
if key not in d:
count=L.count(key)
d[key]=count
n = int(input("How many most common words to print: "))
print("\nOK. The {} most common words are as follows\n".format(n))
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 13
CBSE+2: Python Practical Programs
word_counter = collections.Counter(d)
for word, count in word_counter.most_common(n):
print(word, ": ", count)
fin.close()
#Driver Code
def main():
Read_Email_File()
main()
Output:
How many most common words to print: 4
OK. The 4 most common words are as follows
the : 5
in : 3
of : 3
for : 2
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 14
CBSE+2: Python Practical Programs
9. Create a CSV file by entering user-id and password, read and search the
password for given userid.
import csv
def write():
f=open("C:\\Users\\ranga\\Desktop\\Prctical
File\\details.csv","w",newline='')
wo=csv.writer(f)
wo.writerow(["UserId","Password"])
while True:
u_id=input("Enter User-Id:")
pswd=input("Enter Password:")
data=[u_id,pswd]
wo.writerow(data)
ch=input("Do you want to enter more records(Y/N):")
if ch in 'Nn':
break
f.close()
def read():
f=open("C:\\Users\\ranga\\Desktop\\Prctical File\\details.csv","r")
ro=csv.reader(f)
for i in ro:
print(i)
f.close()
def search():
f=open("C:\\Users\\ranga\\Desktop\\Prctical File\\details.csv","r")
Found=0
u=input("Enter user-id to search:")
ro=csv.reader(f)
next(ro)
for i in ro:
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 15
CBSE+2: Python Practical Programs
if i[0]==u:
print(i[1])
Found=1
f.close()
if Found==0:
print(" Sorry..... no records found")
write()
read()
search()
CSV file
Output:
Enter User-Id: ROHAN
Enter Password: rohan@123
Do you want to enter more records(Y/N): y
Enter User-Id: RANJAN
Enter Password: ranjan@1234
Do you want to enter more records(Y/N): y
Enter User-Id: HEMANTH
Enter Password: hemanth@123
Do you want to enter more records(Y/N): n
['UserId', 'Password']
[' ROHAN', 'rohan@123']
['RANJAN', 'ranjan@1234']
['HEMANTH', 'hemanth@123']
Enter user-id to search: hemanth420
Sorry..... no records found
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 16
CBSE+2: Python Practical Programs
Database Management
● Create a student table and insert data. Implement the following SQL commands on the
student table:
o ALTER table to add new attributes / modify data type / drop attribute
o UPDATE table to modify data
o ORDER By to display data in ascending / descending order
o DELETE to remove tuple(s)
o GROUP BY and find the min, max, sum, count and average
● Integrate SQL with Python by importing suitable module.
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 17
CBSE+2: Python Practical Programs
1. Create Database:
Command:
Output
2. Use Database:
3. Create table:
Command
mysql> Create table student
-> (Rno int primary key,
-> Name varchar(10) NOT NULL,
-> Gender varchar(8),
-> Marks int,
-> Scode varchar(5));
4. Describe the table
Command
mysql>desc student
Output:
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 18
CBSE+2: Python Practical Programs
5. Insert command
mysql> insert into student values(101,'Hemanth','male',420,'s101');
mysql> insert into student values(102,'Vishnu','male',320,'s102');
mysql> insert into student values(103,'Rahul','male',520,'s103');
mysql> insert into student values(104,'Sanjan','female',525,'s104');
mysql> insert into student values(105,'Anamika','female',400,'s105');
mysql> insert into student values(106,'Avanthika','female',430,'s106');
mysql> insert into student values(107,'Likitha','female',480,'s107');
mysql> insert into student values(108,'Arya Jaha','female',333,'s108');
mysql> insert into student values(109,'Md Arshad','male',453,'s109');
mysql> insert into student values(110,'Tanushree','female',483,'s110');
6. SELECT COMMAND
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 19
CBSE+2: Python Practical Programs
7. Select command
8. Select Command
9. ALTER COMMAND (Add Attribute)
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 20
CBSE+2: Python Practical Programs
10. ALTER COMMAND (Drop Attribute)
11. ALTER COMMAND (Modify Data type)
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 21
CBSE+2: Python Practical Programs
12. UPDATE COMMAND (SET Attribute)
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 22
CBSE+2: Python Practical Programs
13. ORDER BY Ascending order
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 23
CBSE+2: Python Practical Programs
ORDER BY Descending Order
14. DELETE COMMAND
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 24
CBSE+2: Python Practical Programs
15. GROUP BY COMMAND
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 25
CBSE+2: Python Practical Programs
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 26
CBSE+2: Python Practical Programs
Prepared By -Ranganath.C, NARAYANA e-Techno School Marathahalli. pg. 27