0% found this document useful (0 votes)
11 views26 pages

Computer Science Practical Python Projects

The document is a practical submission for a Computer Science course at Kendriya Vidyalaya, detailing various Python programs and SQL queries. It includes a table of contents with program descriptions, code snippets, outputs, and explanations of variables and functions used. The practicals cover topics such as basic calculators, file handling, data analysis, and database operations.

Uploaded by

dipoj11803
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)
11 views26 pages

Computer Science Practical Python Projects

The document is a practical submission for a Computer Science course at Kendriya Vidyalaya, detailing various Python programs and SQL queries. It includes a table of contents with program descriptions, code snippets, outputs, and explanations of variables and functions used. The practicals cover topics such as basic calculators, file handling, data analysis, and database operations.

Uploaded by

dipoj11803
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

Kendriya vidyalaya

pushp vihar
Computer Science Practical
Session 2025-26

Submitted By:
Ayush Ranjan
Class – 12th A

Submitted To:
Meena Gupta
Ma'am
INDEX
Page
[Link] Name of the Program / Activity
No.
Python Programs
1 Basic Calculator using functions 1
2 Print all Prime Numbers from 1 to 100 2
3 Find Minimum, Maximum, and Average Marks 3
4 Read text file and display each word separated by ‘#’ 4
Count Vowels, Consonants, Uppercase and
5 5
Lowercase in a file
Remove lines containing character ‘a’ and write to
6 6
another file
7 Print lines starting with ‘T’ or ‘P’ from file 7
8 Count frequency of word ‘He’ and ‘She’ 8
9 Create and Search record in Binary File 9
10 Update marks in Binary File 10
Read CSV file and print items with rate between 500–
12 11
1000
Create CSV file with UserID and Password, search by
13 12
UserID
14 Random Dice Generator 13
15 Linear Search implementation 14
16 Implement Stack using List 15
SQL Queries
Basic Table Commands (CREATE, SHOW,
17 16
DESCRIBE)
18 Insert and Display Records 17
Conditional Queries using WHERE, BETWEEN,
19 18
LIKE
Aggregate and Group Queries (AVG, COUNT,
20 19
SUM)
21 Update and Delete Operations 20
Python–MySQL
Connectivity
22 Create Table in MySQL using Python 21
23 Insert Record in Table using Python 22
24 Fetch Records from Table using Python 23
25 Update Record in Table using Python 24
1. Basic Calculator
AIM : To show functionality of a basic calculator using functions.

CODE
def add(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def div(a,b):
return a/b
print('[Link] [Link] [Link] [Link]')
ch=int(input('Enter choice:'))
a=int(input('Enter first num:'))
b=int(input('Enter second num:'))
if ch==1:
print('Sum:',add(a,b))
elif ch==2:
print('Diff:',sub(a,b))
elif ch==3:
print('Prod:',mul(a,b))
else:
print('Div:',div(a,b))

OUTPUT
Output:
[Link] [Link] [Link] [Link]
Enter choice:1
Enter first num:10
Enter second num:5
Sum: 15

VARIABLES AND FUNCTIONS USED


Name Datatype Purpose

a,b int User inputs

add,sub,mul,div function perform operations

ch int choice input


2. Prime Numbers
AIM : To print all prime numbers from 1 to 100 using a function.

CODE
def is_prime(num):
if num<2:
return False
for i in range(2,num):
if num%i==0:
return False
return True
n=int(input("Enter a number: "))
if is_prime(n):
print(n,"is a prime number")
else:
print(n,"is not a prime number")
print("Prime numbers from 1 to 100 are:")
for i in range(1,101):
if is_prime(i):
print(i,end=' ')

OUTPUT
Output:
Enter a number: 7
7 is a prime number
Prime numbers from 1 to 100 are:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

VARIABLES AND FUNCTIONS USED


Name Datatype Purpose

num,i int check divisibility

is_prime function check prime number


3. Marks Analysis
AIM : To return min, max and average marks from a list.

CODE
def marks(lst):
mn=min(lst)
mx=max(lst)
avg=sum(lst)/len(lst)
return mn,mx,avg
lst=list(map(int,input("Enter marks separated by space: ").split()))
mn,mx,avg=marks(lst)
print('Minimum:',mn,'Maximum:',mx,'Average:',avg)

OUTPUT
Output:
Enter marks separated by space: 45 67 89 90 78
Minimum: 45 Maximum: 90 Average: 73.8

VARIABLES AND FUNCTIONS USED


Name Datatype Purpose

lst list marks list

mn,mx,avg int/float result values


4. Display words separated by #
AIM : To read file line by line and display each word separated by #.

CODE
f=open('[Link]','r')
for line in [Link]():
w=[Link]()
for i in w:
print(i,'#',end='')
[Link]()

OUTPUT
[Link]:
This is my file
Output:
This # is # my # file #

VARIABLES AND FUNCTIONS USED


Name Datatype Purpose

f file text file object

w list words from line


5. Count Vowels, Consonants, Uppercase, Lowercase
AIM : To read a text file and count vowels, consonants, uppercase, lowercase characters.

CODE
f=open('[Link]','r')
v=c=u=l=0
for line in [Link]():
for ch in line:
if [Link]():
if ch in 'AEIOUaeiou':
v+=1
else:
c+=1
if [Link]():
u+=1
if [Link]():
l+=1
print('Vowels:',v,'Cons:',c,'Upper:',u,'Lower:',l)
[Link]()

OUTPUT
[Link]:
This Is My File
Output:
Vowels: 4 Cons: 6 Upper: 4 Lower: 6

VARIABLES AND FUNCTIONS USED


Name Datatype Purpose

f file read file

v,c,u,l int count values


6. Remove lines with 'a'
AIM : To remove all lines containing 'a' and write others to new file.

CODE
f=open('[Link]','r')
f2=open('[Link]','w')
for line in [Link]():
if 'a' not in line:
[Link](line)
[Link]()
[Link]()

OUTPUT
[Link]:
apple
Ball
cat
Dog
Output file ([Link]):
Dog

VARIABLES AND FUNCTIONS USED


Name Datatype Purpose

f,f2 file file objects

line str lines from file


7. Lines starting with T or P
AIM : To print lines starting with T or P.

CODE
f=open('[Link]','r')
for line in [Link]():
if line[0] in 'TtPp':
print(line)
[Link]()

OUTPUT
[Link]:
Tree
People
man
Output:
Tree
People

VARIABLES AND FUNCTIONS USED


Name Datatype Purpose

f file text file

line str line content


8. Count word frequency He/She
AIM : To count frequency of words 'He' and 'She' in a text file.

CODE
f=open('[Link]','r')
he=she=0
for line in [Link]():
w=[Link]()
for i in w:
if [Link]()=='he':
he+=1
elif [Link]()=='she':
she+=1
print('He:',he,'She:',she)
[Link]()

OUTPUT
[Link]:
He is good.
She is kind.
He likes music.
Output:
He: 2 She: 1

VARIABLES AND FUNCTIONS USED


Name Datatype Purpose

f file file object

he,she int count words


9. Search name by roll from binary file
AIM : To create binary file with name, roll and search a roll number.

CODE
import pickle
f=open('[Link]','wb')
n=int(input('Enter n:'))
for i in range(n):
name=input('Enter name:')
r=int(input('Enter roll:'))
[Link]([r,name],f)
[Link]()
f=open('[Link]','rb')
find=int(input('Enter roll to search:'))
found=0
try:
while True:
r=[Link](f)
if r[0]==find:
print('Name:',r[1])
found=1
except:
pass
if found==0:
print('Not found')
[Link]()

OUTPUT
Output:
Enter n:2
Enter name:Ram
Enter roll:1
Enter name:Shyam
Enter roll:2
Enter roll to search:2
Name: Shyam

VARIABLES AND FUNCTIONS USED


Name Datatype Purpose

f file binary file

r,name,find,found various data and search


10. Update marks in binary file
AIM : To update marks in binary file by roll number.

CODE
import pickle
f=open('[Link]','wb')
for i in range(2):
r=int(input('Roll:'))
n=input('Name:')
m=int(input('Marks:'))
[Link]([r,n,m],f)
[Link]()
f=open('[Link]','rb')
data=[]
try:
while True:
[Link]([Link](f))
except:
pass
[Link]()
roll=int(input('Enter roll to update:'))
for i in data:
if i[0]==roll:
i[2]=int(input('New marks:'))
f=open('[Link]','wb')
for i in data:
[Link](i,f)
[Link]()
print('Updated!')

OUTPUT
Output:
Roll:1 Name:Ram Marks:50
Roll:2 Name:Shyam Marks:60
Enter roll to update:1
New marks:90
Updated!

VARIABLES AND FUNCTIONS USED


Name Datatype Purpose

f file binary file

data list store records

roll,i int,list search record


12. Print items with rate 500-1000
AIM : To read CSV file and print items whose rate between 500 and 1000.

CODE
import csv
f=open('[Link]','r')
r=[Link](f)
for i in r:
if 500<=int(i[2])<=1000:
print(i)
[Link]()

OUTPUT
[Link]:
1, Pen,50,10
2, Book,550,5
3, Bag,900,2
Output:
['2','Book','550','5']
['3','Bag','900','2']

VARIABLES AND FUNCTIONS USED


Name Datatype Purpose

f file CSV file

r reader CSV reader object

i list row data


13. UserID Password Search
AIM : To create CSV file and search password for a given user.

CODE
import csv
f=open('[Link]','w',newline='')
w=[Link](f)
for i in range(2):
u=input('Enter userid:')
p=input('Enter pass:')
[Link]([u,p])
[Link]()
f=open('[Link]','r')
uid=input('Enter userid to search:')
r=[Link](f)
for i in r:
if i[0]==uid:
print('Password:',i[1])
[Link]()

OUTPUT
[Link]:
Ayush,1234
Rohan,5678
Output:
Enter userid to search:Ayush
Password:1234

VARIABLES AND FUNCTIONS USED


Name Datatype Purpose

f file CSV file

r,w reader/writer CSV handlers

uid str user input


14. Random Dice
AIM : To simulate dice throw 10 times and print total.

CODE
import random
for i in range(10):
d1=[Link](1,6)
d2=[Link](1,6)
print('Throw',i+1,':',d1+d2)

OUTPUT
Output:
Throw 1 : 7
Throw 2 : 5
Throw 3 : 9
Throw 4 : 4
Throw 5 : 8
Throw 6 : 10
Throw 7 : 6
Throw 8 : 3
Throw 9 : 11
Throw 10 : 7

VARIABLES AND FUNCTIONS USED


Name Datatype Purpose

d1,d2 int random dice values

i int loop counter


15. Linear Search
AIM : To demonstrate linear search in list.

CODE
lst=[10,20,30,40,50]
x=int(input('Enter value to search:'))
for i in range(len(lst)):
if lst[i]==x:
print('Found at',i)
break
else:
print('Not found')

OUTPUT
Output:
Enter value to search:30
Found at 2

VARIABLES AND FUNCTIONS USED


Name Datatype Purpose

lst list elements

x,i int search element,index


16. Stack Using List
AIM : To implement stack using list.

CODE
stack=[]
def push():
val=int(input('Enter value:'))
[Link](val)
print(stack)
def pop():
if len(stack)==0:
print('Empty')
else:
[Link]()
print(stack)
while True:
print('[Link] [Link] [Link]')
ch=int(input('Enter choice:'))
if ch==1:
push()
elif ch==2:
pop()
else:
break

OUTPUT
Output:
[Link] [Link] [Link]
Enter choice:1
Enter value:10
[10]
Enter choice:2
[]

VARIABLES AND FUNCTIONS USED


Name Datatype Purpose

stack list stack container

push,pop function stack ops

ch,val int inputs


SQL Set 1 – Basic Table Commands
AIM : To create database and tables for Student and Marks.

CODE
CREATE DATABASE SchoolDB;
USE SchoolDB;
CREATE TABLE Student(Roll INT PRIMARY KEY, Name VARCHAR(20), Class INT, Section
CHAR(1));
CREATE TABLE Marks(Roll INT, Subject VARCHAR(20), Marks INT);
SHOW TABLES;
DESCRIBE Student;

OUTPUT
Output:
Database changed
Query OK, 0 rows affected

Tables_in_SchoolDB
-------------------
Marks
Student

DESCRIBE Student;
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| Roll | int | NO | PRI | NULL | |
| Name | varchar(20) | YES | | NULL | |
| Class | int | YES | | NULL | |
| Section| char(1) | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
SQL Set 2 – Insert and Display
AIM : To insert and display data from Student and Marks tables.

CODE
INSERT INTO Student VALUES(1,'Ayush',12,'A');
INSERT INTO Student VALUES(2,'Rohan',12,'A');
INSERT INTO Marks VALUES(1,'Math',90);
INSERT INTO Marks VALUES(2,'Math',80);
SELECT * FROM Student;
SELECT * FROM Marks;

OUTPUT
Output:
Query OK, 1 row affected
Query OK, 1 row affected

SELECT * FROM Student;


+------+--------+-------+---------+
| Roll | Name | Class | Section |
+------+--------+-------+---------+
| 1 | Ayush | 12 | A |
| 2 | Rohan | 12 | A |
+------+--------+-------+---------+

SELECT * FROM Marks;


+------+--------+-------+
| Roll | Subject| Marks |
+------+--------+-------+
| 1 | Math | 90 |
| 2 | Math | 80 |
+------+--------+-------+
SQL Set 3 – Conditional Queries
AIM : To perform conditional queries on the tables.

CODE
SELECT Name FROM Student WHERE Class=12 AND Section='A';
SELECT * FROM Marks WHERE Marks BETWEEN 80 AND 100;
SELECT DISTINCT Subject FROM Marks;
SELECT * FROM Student WHERE Name LIKE 'A%';

OUTPUT
Output:
+--------+
| Name |
+--------+
| Ayush |
| Rohan |
+--------+

+------+--------+-------+
| Roll | Subject| Marks |
+------+--------+-------+
| 1 | Math | 90 |
| 2 | Math | 80 |
+------+--------+-------+

+---------+
| Subject |
+---------+
| Math |
+---------+

+------+--------+-------+---------+
| Roll | Name | Class | Section |
+------+--------+-------+---------+
| 1 | Ayush | 12 | A |
+------+--------+-------+---------+
SQL Set 4 – Aggregate and Group Queries
AIM : To use aggregate functions and grouping.

CODE
SELECT Subject, AVG(Marks) FROM Marks GROUP BY Subject;
SELECT COUNT(*) FROM Student;
SELECT MAX(Marks), MIN(Marks) FROM Marks;
SELECT Subject, SUM(Marks) FROM Marks GROUP BY Subject HAVING SUM(Marks)>150;

OUTPUT
Output:
+---------+------------+
| Subject | AVG(Marks) |
+---------+------------+
| Math | 85.00 |
+---------+------------+

+----------+
| COUNT(*) |
+----------+
|2 |
+----------+

+------------+------------+
| MAX(Marks) | MIN(Marks) |
+------------+------------+
| 90 | 80 |
+------------+------------+

+---------+------------+
| Subject | SUM(Marks) |
+---------+------------+
| Math | 170 |
+---------+------------+
SQL Set 5 – Update and Delete
AIM : To update and delete records from table.

CODE
UPDATE Marks SET Marks=95 WHERE Roll=1;
SELECT * FROM Marks;
DELETE FROM Marks WHERE Roll=2;
SELECT * FROM Marks;

OUTPUT
Output:
Query OK, 1 row affected

+------+--------+-------+
| Roll | Subject| Marks |
+------+--------+-------+
| 1 | Math | 95 |
| 2 | Math | 80 |
+------+--------+-------+

Query OK, 1 row affected

+------+--------+-------+
| Roll | Subject| Marks |
+------+--------+-------+
| 1 | Math | 95 |
+------+--------+-------+
1. Create Table in MySQL
AIM : To connect Python with MySQL and create a table.

CODE
import [Link] as m
con=[Link](host='localhost',user='root',passwd='password',database='SchoolDB')
cur=[Link]()
[Link]('create table student(Roll int primary key, Name varchar(20))')
print('Table created')
[Link]()

OUTPUT
Output:
Table created

mysql> SHOW TABLES;


+----------------+
| Tables_in_SchoolDB |
+----------------+
| student |
+----------------+

VARIABLES AND FUNCTIONS USED


Name Datatype Purpose

m module used for MySQL connection

con object connection to MySQL

cur object cursor to execute queries


2. Insert Record in Table
AIM : To insert record in MySQL table using Python.

CODE
import [Link] as m
con=[Link](host='localhost',user='root',passwd='password',database='SchoolDB')
cur=[Link]()
r=int(input('Enter roll:'))
n=input('Enter name:')
[Link]('insert into student values(%s,%s)',(r,n))
[Link]()
print('Record inserted')
[Link]()

OUTPUT
Output:
Enter roll: 1
Enter name: Ayush
Record inserted

mysql> SELECT * FROM student;


+------+--------+
| Roll | Name |
+------+--------+
| 1 | Ayush |
+------+--------+

VARIABLES AND FUNCTIONS USED


Name Datatype Purpose

m module used for connection

con object MySQL connection

cur object cursor object

r,n var user inputs


3. Fetch Records from Table
AIM : To fetch and display records using Python.

CODE
import [Link] as m
con=[Link](host='localhost',user='root',passwd='password',database='SchoolDB')
cur=[Link]()
[Link]('select * from student')
data=[Link]()
for i in data:
print(i)
[Link]()

OUTPUT
Output:
(1, 'Ayush')
(2, 'Rohan')

VARIABLES AND FUNCTIONS USED


Name Datatype Purpose

m module for MySQL

con object database connection

cur object execute query

data list fetched data


4. Update Record in Table
AIM : To update record in MySQL table using Python.

CODE
import [Link] as m
con=[Link](host='localhost',user='root',passwd='password',database='SchoolDB')
cur=[Link]()
r=int(input('Enter roll to update:'))
n=input('Enter new name:')
[Link]('update student set Name=%s where Roll=%s',(n,r))
[Link]()
print('Record updated')
[Link]()

OUTPUT
Output:
Enter roll to update: 1
Enter new name: Ayush R
Record updated

mysql> SELECT * FROM student;


+------+----------+
| Roll | Name |
+------+----------+
| 1 | Ayush R |
| 2 | Rohan |
+------+----------+

VARIABLES AND FUNCTIONS USED


Name Datatype Purpose

m module for connection

con object connection

cur object cursor

r,n var user inputs

You might also like