0% found this document useful (0 votes)
14 views13 pages

Python Practical Programs for Students

The document outlines a series of Python programming exercises for a Computer Science curriculum, including functions for prime checking, summing even and odd numbers, analyzing student marks, and file operations. It also includes practical tasks involving binary and CSV file manipulations, as well as MySQL queries for database operations related to student records. Each exercise is accompanied by sample code solutions.

Uploaded by

perveenxuzmind
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views13 pages

Python Practical Programs for Students

The document outlines a series of Python programming exercises for a Computer Science curriculum, including functions for prime checking, summing even and odd numbers, analyzing student marks, and file operations. It also includes practical tasks involving binary and CSV file manipulations, as well as MySQL queries for database operations related to student records. Each exercise is accompanied by sample code solutions.

Uploaded by

perveenxuzmind
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DR.

SAVITA MEMORIAL GLOBAL ACADEMY CHUNAR Type yo

COMPUTER SCIENCE: XII


AISSCE (Practical) 2025-26
List of Practicals
Exp:1 Write a function in python IsPrime(), which accept a number and returns True if the
number is a prime number otherwise return False. Use this function to print all prime
numbers from given range.
Sol-1 #Program to check and print Prime number for given range.
def IsPrime(num):
prime=True
for i in range(2, num):
if num % i == 0:
prime=False
return prime
# Main Program
start= int(input(“Enter starting range”))
end= int(input(“Enter ending range”))
for num in range(start, end+1):
if IsPrime(num):
print(num, end= “ ” )
Exp:2 Write Python program SumEvenOdd() which accepts a list of numbers and returns sum
of even and odd numbers in the list.
Sol-2 #Program to get sum of even and odd numbers in the list.
def SumEvenOdd(lst):
sm=0
od=0
for i in lst:
if i%2 == 0:
sm=sm+i
else:
od=od+i
return sm, od
# Main Program
lst=eval(input(“Enter list of numbers”))
s,o=SumEvenOdd(lst)
print(“Sum of Even numbers”, s)
print(“Sum of Odd numbers”, o)
Exp:3 Write a function MarksAnalysis() in python which accept a list of marks of students and
return the minimum mark, maximum mark and the average marks.
Sol-3 #Program to get Maximum, Minimum and average marks in the list.
def MarksAnalysis(lst):
mx=max(lst)
mn=min(lst)
avg=sum(lst)/len(lst)
return mx,mn,avg
# Main Program
lst=eval(input(“Enter list of marks”))
mx,mn,avg=MarksAnalysis(lst)
print(“Maximum Marks : ”, mx)
print(“Minimum Marks : ”, mn)
print(“Avaerage Marks : ”, avg)
Exp:4 Write a python function CountWord() which accept a string and a word and returns
number of occurrences of the given word in the string.
Sol-4 #Program to find the occurrence of any word in a string.
def countWord(str1,word):
s = [Link]()
count=0
for w in s:
if w==word:
count+=1
return count
#Main Program
str1 = input("Enter any sentence :")
word=input("Enter word to search in sentence :")
count = countWord(str1,word)
if count==0:
print( word," not present in the sentence. ")
else:
print(word," occurs ",count," times.")
Exp:5 Write a Python program to read a text file “[Link]” line by line and display each word
separated by a #.
Sol-5 #Program to read content of file line by line and words separated by '#'
f = open("[Link]")
for line in f:
words = [Link]()
for w in words:
print(w+'#',end='')
print()
[Link]()
Exp:6 Write a Python program to read a text file “[Link]” and display the number of vowels/
consonants/ uppercase/ lowercase characters in the file.
Sol-6 #Program to read content of file and display total number of
# vowels, consonants, lowercase and uppercase characters
f = open("[Link]")
v=0
c=0
u=0
l=0
o=0
data = [Link]()
vowels=['a','e','i','o','u']
for ch in data:
if [Link]():
if [Link]() in vowels:
v+=1
else:
c+=1
if [Link]():
u+=1
elif [Link]():
l+=1
else:
o+=1
print("Total Vowels in file :",v)
print("Total Consonants in file n :",c)
print("Total Capital letters in file :",u)
print("Total Small letters in file :",l)
print("Total Other than letters :",o)
[Link]()
Exp:7 Write a Python program to remove all the lines that contain the character `a' in a file and
write it to another file.
Sol-7 #Program to read a file and all lines excluding lines
# containing ‘a’ letter in another file.
f1 = open("[Link]")
f2 = open("[Link]","w")
for line in f1:
if 'a' not in line:
[Link](line)
print(“File Created Successfully.”)
[Link]()
[Link]()
Exp:8 Write a Python program to create a text file and print the lines starting with ‘T’ or ‘P’.
(Both uppercase and lowercase).
Sol-8 #Program to create and read file and display all lines starting with T or P.
f = open("[Link]",”w”)
for i in range(5):
txt=input (“Enter a line of text”)
[Link](txt)
[Link](“\n”)
[Link]()
f=open("[Link]","r")
for line in f:
if line[0] in [‘T’, ‘t’, ‘P’, ‘p’ ]:
print(line, end=’’)
[Link]()
Exp:9 Write a Python program to read a text file to print the frequency of the word ‘He’ and
‘She’ found in the file.
Sol-9 #Program to read a file and count ‘He’ and ‘She’ word.
f=open("[Link]","r")
count=0
txt=[Link]()
wlist=[Link]()
for word in wlist:
if word==’He’ or word==’She’:
count+=1
[Link]()
print("He and She word occurred ",count," times")
Exp:10 Write a Python program to read a text file and count number of words and lines stored in
a text file.
Sol-10 #Program to read a file and count words and lines.
f = open("[Link]")
lcount=0
wcount=0
for line in f:
lcount+=1
wlist = [Link]()
wcount=wcount+len(wlist)
print(“Total lines=”, lcount)
print(“Total words”, wcount)
Exp:11 Write a Python program to create a binary file with name and roll number of student and
display the data by reading the file.
Sol-11 #Program to create a binary file to store Rollno and name and display
import pickle
#create binary file
student=[]
f=open('[Link]','wb')
ans='y'
while ans=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
[Link]([roll,name])
ans=input("Add More y/n?")
[Link](student,f)
[Link]()
#read Binary File
f=open('[Link]','rb')
student=[]
student = [Link](f)
for rec in student:
print(“Roll No :”,rec[0])
print(“Name :”, rec[1])
[Link]()
Exp:12 Write a Python program to 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.
Sol-12 #Program to create a binary file and search a record
import pickle
#create binary file
student=[]
f=open('[Link]','wb')
ans='y'
while ans=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
[Link]([roll,name])
ans=input("Add More y/n?")
[Link](student,f)
[Link]()
#read Binary File
f=open('[Link]','rb')
student=[]
student = [Link](f)
ans=’y’
while ans=='y':
found=False
r= int(input("Enter Roll number to be searched :"))
for rec in student:
if rec[0]==r:
print("Name is :",rec[1])
found=True
break
if not found:
print("Sorry! Roll number not found")
ans=input("Search more y/n :")
[Link]()
Exp:13 Write a Python program to create a binary file with roll number, name and marks. Input a
roll number and update the marks.
Sol-13 #Program to create a binary file and search and update record
import pickle
#create binary file
student=[]
f=open('[Link]','wb')
ans='y'
while ans=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
marks= int(input(“Enter Marks:”))
[Link]([roll,name, marks])
ans=input("Add More y/n?")
[Link](student,f)
[Link]()
#read Binary File and update record
f=open('[Link]','rb')
student=[]
student = [Link](f)
[Link]()
ans=’y’
while ans=='y':
found=False
r= int(input("Enter Roll number to be updated :"))
for rec in student:
if rec[0]==r:
print(“Record found…”)
print("Name is :",rec[1])
print(“Current Marks is :”, rec[2])
m=int(input(“Enter new Marks”))
rec[2]=m # update mark in the list
found=True
break
if not found:
print("Sorry! Roll number not found")
ans=input("More update y/n :")
[Link]()
f=open('[Link]','wb')
[Link](student,f) # write updated list in the file
[Link]()
Exp:14 Write a Python program to create a CSV file to store Empno, Name, Salary of employees.
Read CSV file and search any empno and display name, salary if found, otherwise display
appropriate message.
Sol-14 import csv
with open('[Link]',mode='a') as csvfile:
mywriter = [Link](csvfile,delimiter=',')
ans='y'
while ans=='y':
eno=int(input("Enter Employee Number "))
name=input("Enter Employee Name ")
salary=int(input("Enter Employee Salary :"))
[Link]([eno,name,salary])
ans=input("Add More ?")
ans='y'
with open('[Link]',mode='r') as csvfile:
myreader = [Link](csvfile, delimiter=',')
while ans=='y':
found=False
e = int(input("Enter Employee Number to search :"))
for row in myreader:
if len(row)!=0:
if int(row[0])==e:
print(" Record Found")
print("NAME :",row[1])
print("SALARY :",row[2])
found=True
break
if found==False:
print(" EMPNO NOT FOUND")
ans = input("Search More y/n")
Exp:15 Write a Python program to create a CSV file by entering user-id and password, read and
search the password for given userid
Sol-15 import csv
with open('[Link]',mode='a') as csvfile:
mywriter = [Link](csvfile,delimiter=',')
ans='y'
while ans=='y':
uid=input("Enter User ID:"))
pass=input("Enter password: ")
[Link]([uid,pass])
ans=input("Add More ?")
ans='y'
with open('[Link]',mode='r') as csvfile:
myreader = [Link](csvfile,delimiter=',')
while ans=='y':
found=False
u = input("Enter User ID to search :"))
for row in myreader:
if len(row)!=0:
if row[0]==u:
print(" Record Found")
print("Password is :",row[1])
found=True
break
if not found:
print(" USER ID NOT FOUND")
ans = input("Search More y/n")
Exp:16 Write a Python program to implement a stack using a list data-structure.
Sol-16 def Push(S,item):
[Link](item)
def Pop(S):
if len(S)==0:
print(“Stack is Empty”)
else:
val=[Link]()
print(“Deleted item is :” , val)
def Show(S):
if len(S)==0:
print("Stack is empty")
else:
t = len(S)-1
while(t>=0):
print(S[t])
t-=1
# main program
S=[]
while True:
print("**** STACK OPERATION ******")
print("1. PUSH ")
print("2. POP")
print("3. SHOW STACK ")
print("0. EXIT")
ch = int(input("Enter your choice :"))
if ch==1:
val = int(input("Enter Item to Push :"))
Push(S,val)
elif ch==2:
Pop(S)
elif ch==3:
Show(S)
elif ch==0:
print("Bye")
break
Exp:17 Write the MySQL query for the following task.
(a) Create a database SCHOOL
(b) Create a table STUDENTS with the following structure.
Column Name Data type Constraints
ST_ID Int(4) Primary Key
RNo Int(2) Not null
Name Char(50) Not null
Class Int(2)
Gender Char(1)
DOB Date
Marks Int(2)
(c) Display structure of the table
(d) Add another column MobileNo enable to store 10 character/digit mobile number.
(e) Insert some records (at least 10) in the Student table.
Sol-17 (a) CREATE DATABASE SCHOOL;
(b) CREATE TABLE STUDENTS (ST_ID int(4) PRIMARY KEY NOT NULL,
RNo int(2) NOT NULL, Name char(50) NOT NULL, Class int(2), Gender char(1),
DOB date, Marks int(2));
(c) DESC STUDENTS;
(d) ALTER TABLE STUDENTS ADD MobileNo char(10);
(e) INSERT INTO STUDENTS VALUES(1001, 5, “AMAR KANT”,12,’M’,
”1990-10-12”,65,”9450342350”)
Exp:18 Write the MySQL query for the following using Student Table.
(a) Display all female students’ records of class 12
(b) Display name and class of all students who secured more than 80 marks.
(c) Delete a record whose ST_ID is 110.
(d) Increase existing marks by 5 for those female students who secured less than 20
marks.
(e) Decrease existing marks by 3 of class 10 who secured more than 90 marks.
Sol-18 (a) SELECT * FROM STUDENTS WHERE Gender=”F” AND Class=12;
(b) SELECT Name, Class FROM STUDENTS WHERE Marks>80;
(c) DELETE FROM STUDENTS WHERE ST_ID=110;
(d) UPDATE STUDENTS SET Marks = Marks+5 WHERE Marks < 20 AND Gender=”F”;
(e) UPDATE STUDENTS SET Marks = Marks-3 WHERE Marks > 90 AND Class=10;
Exp:19 Write the MySQL query for the following using Student Table.
(a) Display all students’ records whose name contains ‘Singh’ in alphabetical order of
name.
(b) Display all students’ records whose name contains ‘a’ as second alphabet in their
name.
(c) Display name, class and marks of all students who secured greater or equal to 30
and less than equal to 50.
(d) Display name of students who are born on or before 1st Jan 2012.
(e) Display name, marks of students in descending order of marks.
Sol-19 (a) SELECT * FROM STUDENTS WHERE Name LIKE “%Singh%” ORDER BY Name;
(b) SELECT * FROM STUDENTS WHERE Name LIKE “_a%” ;
(c) SELECT Name, Class, Marks FROM STUDENTS WHERE Marks BETWEEN 30 AND
50;
(d) SELECT Name FROM STUDENTS WHERE DOB <= “2012-01-01”;
(e) SELECT Name, Marks FROM STUDENTS ORDER BY Marks DESC;
Exp:20 Write the MySQL query for the following using Student Table.
(a) Display maximum, minimum and average marks of class 10.
(b) Display number of students who secured more than 80 marks.
(c) Display class wise numbers of students in the table.
(d) Display maximum and minimum marks secured by students for each class.
(e) Display number of students for each class who secured more than 80 marks.
Sol-20 (a) SELECT MAX(Marks), MIN(Marks), AVG(Marks) FROM STUDENTS WHERE
Class=10;
(b) SELECT COUNT(*) FROM STUDENTS WHERE Marks>80;
(c) SELECT Class, COUNT(*) FROM STUDENTS GROUP BY Class;
(d) SELECT Class, MAX(Marks), MIN(Marks) FROM STUDENTS GROUP BY Class;
(e) SELECT Class, COUNT(*) FROM STUDENTS GROUP BY Class HAVING Marks>80;
Exp:21 Consider the following two tables named Students and Teachers having some records.
STUDENTS (STCode, SName, Class, Stream, TeacherID)
TEACHERS (TeacherID, TName, Subject, Pay, Post)
Write the MySQL query for the following.
(a) Display name of students, class, stream and teacher name of class 10.
(b) Display name of student who are taught by teacher named “Ajay Kumar”
(c) Display details of teachers and who are teaching Science in class 10.
(d) Display details all PGTs who are teaching in class 12.
(e) Display details of students along with teachers name from Science stream.
Sol-21 (a) SELECT SName, Class, Stream, TName from STUDENTS, TEACHERS WHERE
[Link]= [Link];
(b) SELECT SName from STUDENTS, TEACHERS WHERE [Link]=
[Link] AND TName=”Ajay Kumar”;
(c) SELECT TEACHERS.* from STUDENTS, TEACHERS WHERE [Link]=
[Link] AND Subject=”Science” AND Class=10;
(d) SELECT TEACHERS.* from STUDENTS, TEACHERS WHERE [Link]=
[Link] AND Post=”PGT” AND Class=12;
(e) SELECT STUDENTS.*, TName from STUDENTS, TEACHERS WHERE
[Link]= [Link] AND Stream=”Science”;
Exp:22 Write a Python program to connect with Student Table of School database and display all
records of students.
Sol-22 import [Link] as mycon
con = [Link](host='localhost', user='root', password="",
database=’school’)
cur = [Link]()
[Link]("select * from students")
result = [Link]()
for row in result:
print(row)
[Link]()
Exp:23 Write a Python program to connect with Student table of School database and search
given StudentID in the Students table and display record. If given StudentId not found
then display appropriate message.
Sol-23 import [Link] as mycon
con = [Link](host='localhost', user='root', password="", database=
“school”)
cur = [Link]()
ans=’y’
while ans==’y’
sid= input(“Enter Student ID to be searched”)
qry= “select * from students where st_id=” +sid
[Link](qry)
result=[Link]()
if result == None:
print(“No record found”)
else:
print(result)
ans=input(“More search y/n”)
Exp:24 Write a Python program to update a record (Marks field) for given StudentID in Student
table of School database.
Sol-24 import [Link] as mycon
con = [Link](host='localhost', user='root', password="", database=
“school”)
cur = [Link]()
ans=’y’
while ans==’y’
sid= input(“Enter Student ID to be updated”)
qry= “select * from students where st_id=” +sid
[Link](qry)
result=[Link]()
if result == None:
print(“No such record found for given Student ID”)
else:
print(“Record Found…)
print(result)
m=input(“Enter new marks”)
qry= “update students set marks={ } where st_is={ }”.format(m,sid)
[Link](qry)
[Link]()
print(“Record updated successfully”)
ans=input(“More update y/n”)
[Link]()
Exp:25 Write a Python program to delete the record of entered StudentId in Student table of
School database.
Sol-25 import [Link] as mycon
con = [Link](host='localhost', user='root', password="", database=
“school”)
cur = [Link]()
ans=’y’
while ans==’y’
sid= input(“Enter Student ID to be deleted”)
qry= “select * from students where st_id=” +sid
[Link](qry)
result=[Link]()
if result == None:
print(“No such record found for given Student ID”)
else:
print(“Record Found…)
print(result)
qry= “delete from students where st_is={ }”.format(sid)
[Link](qry)
[Link]()
print(“Record deleted successfully”)
ans=input(“More delete y/n”)
[Link]()

You might also like