0% found this document useful (0 votes)
3 views24 pages

Practical Comp

The document contains practical programming exercises for Class XII Computer Science, including tasks such as checking for prime numbers, calculating the sum of a list recursively, generating Fibonacci series, and searching for words in strings. It also covers file handling, including reading and writing files, and creating binary and CSV files to manage student and employee records. Additionally, it includes a stack implementation using Python lists.

Uploaded by

tevali3488
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)
3 views24 pages

Practical Comp

The document contains practical programming exercises for Class XII Computer Science, including tasks such as checking for prime numbers, calculating the sum of a list recursively, generating Fibonacci series, and searching for words in strings. It also covers file handling, including reading and writing files, and creating binary and CSV files to manage student and employee records. Additionally, it includes a stack implementation using Python lists.

Uploaded by

tevali3488
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

COMPUTER SCIENCE

Subject Code – 083


Class XII (2026-27)
PRACTICAL PROGRAMS
1. Input any number from user and check whether it is Prime or not
# Program to input any number from user
# Check whether it is a Prime number or not

import math

num = int(input("Enter any number: "))


isPrime = True

for i in range(2, int([Link](num)) + 1):


if num % i == 0:
isPrime = False
break

if isPrime:
print("## Number is Prime ##")
else:
print("## Number is not Prime ##")

OUTPUT:
Enter any number: 117
## Number is not Prime ##

Enter any number: 119


## Number is not Prime ##

Enter any number: 113


## Number is Prime ##

Enter any number: 7


## Number is Prime ##

Enter any number: 19


## Number is Prime ##

1|Pag e
2. Write a program to find sum of elements of a list recursively
# Program to find sum of elements of list recursively

def findSum(lst, num):


if num == 0:
return 0
else:
return lst[num - 1] + findSum(lst, num - 1)

mylist = [] # Empty List

# Loop to input elements in list


num = int(input("Enter how many numbers: "))
for i in range(num):
n = int(input("Enter Element " + str(i + 1) + ": "))
[Link](n) # Adding number to list

sum = findSum(mylist, len(mylist))

print("Sum of List items", mylist, "is:", sum)

OUTPUT:

Enter how many numbers: 6


Enter Element 1: 10
Enter Element 2: 20
Enter Element 3: 30
Enter Element 4: 40
Enter Element 5: 50
Enter Element 6: 60
Sum of List items [10, 20, 30, 40, 50, 60] is: 210

2|Pag e
3. Write a program to calculate the nth term of Fibonacci series
# Program to find nth term of Fibonacci series
# Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# nth term will be counted from 1 (not 0)

def nthfiboterm(n):
if n <= 1:
return n
else:
return nthfiboterm(n - 1) + nthfiboterm(n - 2)

num = int(input("Enter the 'n' term to find in Fibonacci: "))


term = nthfiboterm(num)

print(num, "th term of Fibonacci series is:", term)

OUTPUT:

Enter the 'n' term to find in Fibonacci: 10


10 th term of Fibonacci series is: 55

3|Pag e
4. Program to search any word in a given string/sentence
# 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

str1 = input("Enter any sentence: ")


word = input("Enter word to search in sentence: ")

count = countWord(str1, word)

if count == 0:
print("## Sorry!", word, "not present ##")
else:
print("##", word, "occurs", count, "times ##")

OUTPUT:
Enter any sentence: my computer your computer our computer everyones computer
Enter word to search in sentence: computer
## computer occurs 4 times ##

Enter any sentence: learning python is fun


Enter word to search in sentence: java
## Sorry! java not present ##

4|Pag e
5. Read and display file content line by line with each word separated by ‘#’
# Program to read content of file line by line
# and display each word separated by '#'

f = open("[Link]")

for line in f:
words = [Link]()
for w in words:
print(w + '#', end='')
print()

[Link]()

NOTE: If the original content of file is:


India is my country
I love python
Python learning is fun

OUTPUT:
India#is#my#country#
I#love#python#
Python#learning#is#fun#

5|Pag e
6. Read file content and display total number of vowels, consonants, uppercase and lowercase
characters

# Program to read content of file


# and display total number of vowels, consonants,
# lowercase and uppercase characters

f = open("[Link]")

v=0 # vowels
c=0 # consonants
u=0 # uppercase
l=0 # lowercase
o=0 # other characters

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
elif ch != ' ' and ch != '\n':
o += 1
print("Total Vowels in file :", v)
print("Total Consonants in file :", c)
print("Total Capital letters in file :", u)
print("Total Small letters in file :", l)
print("Total Other than letters :", o)
[Link]()

NOTE: If the file content is:

India is my country
I love python
Python learning is fun
123@

OUTPUT:

Total Vowels in file : 16


Total Consonants in file : 30
Total Capital letters in file : 2
Total Small letters in file : 44
Total Other than letters :4

6|Pag e
7. Create a binary file to store Rollno and Name, search Rollno and display result
# Program to create a binary file to store Rollno and Name
# Search for Rollno and display record if found
# otherwise "Roll no. not found"

import pickle

student = []

# Writing data to binary file


f = open('[Link]', 'wb')

ans = 'y'
while [Link]() == 'y':
roll = int(input("Enter Roll Number: "))
name = input("Enter Name: ")
[Link]([roll, name])
ans = input("Add More ? (Y): ")

[Link](student, f)
[Link]()

# Reading data from binary file


f = open('[Link]', 'rb')

student = []
while True:
try:
student = [Link](f)
except EOFError:
break

# Searching record
ans = 'y'
while [Link]() == 'y':
found = False
r = int(input("Enter Roll number to search: "))

for s in student:
if s[0] == r:
print("## Name is :", s[1], "##")
found = True
break

if not found:
7|Pag e
print("#### Sorry! Roll number not found ####")

ans = input("Search more? (Y): ")

[Link]()

OUTPUT:
Enter Roll Number: 1
Enter Name: Amit
Add More ? (Y): y

Enter Roll Number: 2


Enter Name: Jasbir
Add More ? (Y): y

Enter Roll Number: 3


Enter Name: Vikral
Add More ? (Y): n

Enter Roll number to search: 2


## Name is : Jasbir ##
Search more? (Y): y

Enter Roll number to search: 1


## Name is : Amit ##
Search more? (Y): y

Enter Roll number to search: 4


#### Sorry! Roll number not found ####
Search more? (Y): n

8|Pag e
8. Create a binary file to store Rollno, Name and Marks and update marks of a given Rollno

# Program to create a binary file to store Rollno, Name and Marks


# Search for Rollno and update marks if found

import pickle

student = []

# Writing data to binary file


f = open('[Link]', 'wb')

ans = 'y'
while [Link]() == '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): ")

[Link](student, f)
[Link]()

# Reading data from binary file


f = open('[Link]', 'rb+')

student = []
while True:
try:
student = [Link](f)
except EOFError:
break

# Updating record
ans = 'y'
while [Link]() == 'y':
found = False
r = int(input("Enter Roll number to update: "))

for s in student:
if s[0] == r:
print("## Name is:", s[1], "##")
print("## Current Marks is:", s[2], "##")

m = int(input("Enter new marks: "))


9|Pag e
s[2] = m

print("## Record Updated ##")


found = True
break

if not found:
print("#### Sorry! Roll number not found ####")

ans = input("Update more ? (Y): ")

[Link]()

OUTPUT:

Enter Roll Number: 1


Enter Name: Amit
Enter Marks: 99
Add More ? (Y): y

Enter Roll Number: 2


Enter Name: Vikrant
Enter Marks: 88
Add More ? (Y): y

Enter Roll Number: 3


Enter Name: Nitin
Enter Marks: 66
Add More ? (Y): n

Enter Roll number to update: 2


## Name is: Vikrant ##
## Current Marks is: 88 ##
Enter new marks: 90
## Record Updated ##
Update more ? (Y): y

Enter Roll number to update: 2


## Name is: Vikrant ##
## Current Marks is: 90 ##
Enter new marks: 95
## Record Updated ##
Update more ? (Y): n

10 | P a g e
9. Read file line by line and write to another file except lines containing 'a'

# Program to read lines from a file and write to another file


# except those lines which contain letter 'a'

f1 = open("[Link]")
f2 = open("[Link]", "w")

for line in f1:


if 'a' not in line:
[Link](line)

print("## File Copied Successfully! ##")

[Link]()
[Link]()

OUTPUT:

## File Copied Successfully! ##

After copying, content of [Link] will be:

one two three four


five six seven
eight nine ten
bye!

11 | P a g e
10. Create CSV file to store empno, name, salary and search empno

# Program to create CSV file and store empno, name, salary


# and search any empno to display name and salary

import csv

# Writing data to CSV file


with open('[Link]', mode='a', newline='') as csvfile:
mywriter = [Link](csvfile, delimiter=',')
ans = 'y'

while [Link]() == 'y':


eno = int(input("Enter Employee Number: "))
name = input("Enter Employee Name: ")
salary = int(input("Enter Employee Salary: "))

[Link]([eno, name, salary])


print("## Data Saved... ##")

ans = input("Add More? (Y): ")

# Reading and searching data


ans = 'y'
while [Link]() == 'y':
found = False
e = int(input("Enter Employee Number to search: "))

with open('[Link]', mode='r') as csvfile:


myreader = [Link](csvfile, delimiter=',')

for row in myreader:


if len(row) != 0:
if int(row[0]) == e:
print("============================")
print("NAME :", row[1])
print("SALARY :", row[2])
print("============================")
found = True
break

if not found:
print("==========================")
print(" EMPNO NOT FOUND")
print("==========================")
12 | P a g e
ans = input("Search More? (Y): ")

OUTPUT:

Enter Employee Number: 1


Enter Employee Name: Amit
Enter Employee Salary: 90000
## Data Saved... ##
Add More? (Y): y

Enter Employee Number: 2


Enter Employee Name: Sunil
Enter Employee Salary: 80000
## Data Saved... ##
Add More? (Y): y

Enter Employee Number: 3


Enter Employee Name: Satya
Enter Employee Salary: 75000
## Data Saved... ##
Add More? (Y): n

Enter Employee Number to search: 2


============================
NAME : Sunil
SALARY : 80000
============================
Search More? (Y): y

Enter Employee Number to search: 3


============================
NAME : Satya
SALARY : 75000
============================
Search More? (Y): y

Enter Employee Number to search: 4


==========================
EMPNO NOT FOUND
==========================
Search More? (Y): n

13 | P a g e
11. Implement Stack in Python using List

# Stack Implementation using List

def isEmpty(S):
return len(S) == 0

def Push(S, item):


[Link](item)

def Pop(S):
if isEmpty(S):
return "Underflow"
else:
return [Link]()

def Peek(S):
if isEmpty(S):
return "Underflow"
else:
return S[-1]

def Show(S):
if isEmpty(S):
print("Sorry! No items in Stack")
else:
print("(Top)", end=' ')
for i in range(len(S) - 1, -1, -1):
print(S[i], "<==", end=' ')
print()

# Main Program
S = [] # Stack

while True:
print("**** STACK DEMONSTRATION ******")
print("1. PUSH")
print("2. POP")
print("3. PEEK")
print("4. SHOW STACK")
print("0. EXIT")

ch = int(input("Enter your choice: "))

if ch == 1:
14 | P a g e
val = int(input("Enter Item to Push: "))
Push(S, val)

elif ch == 2:
val = Pop(S)
if val == "Underflow":
print("Stack is Empty")
else:
print("Deleted Item was:", val)

elif ch == 3:
val = Peek(S)
if val == "Underflow":
print("Stack Empty")
else:
print("Top Item:", val)

elif ch == 4:
Show(S)

elif ch == 0:
print("Bye")
break

else:
print("Invalid Choice")

OUTPUT:

**** STACK DEMONSTRATION ******


1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT

Enter your choice: 1


Enter Item to Push: 10

Enter your choice: 1


Enter Item to Push: 20

Enter your choice: 1


Enter Item to Push: 30

15 | P a g e
Enter your choice: 4
(Top) 30 <== 20 <== 10 <==

Enter your choice: 3


Top Item: 30

Enter your choice: 2


Deleted Item was: 30

Enter your choice: 4


(Top) 20 <== 10 <==

Enter your choice: 0

16 | P a g e
12. Connect with database, store employee records and display them
# Program to connect with database and store/display employee records

import [Link] as mycon

# Establish connection
con = [Link](host='[Link]', user='root', password="admin")
cur = [Link]()

# Create database and table


[Link]("CREATE DATABASE IF NOT EXISTS company")
[Link]("USE company")

[Link]("""
CREATE TABLE IF NOT EXISTS employee(
empno INT,
name VARCHAR(20),
dept VARCHAR(20),
salary INT
)
""")

[Link]()

choice = None

while choice != 0:
print("1. ADD RECORD")
print("2. DISPLAY RECORD")
print("0. EXIT")

choice = int(input("Enter Choice: "))

if choice == 1:
e = int(input("Enter Employee Number: "))
n = input("Enter Name: ")
d = input("Enter Department: ")
s = int(input("Enter Salary: "))

query = "INSERT INTO employee VALUES({}, '{}', '{}', {})".format(e, n, d, s)


[Link](query)
[Link]()

print("## Data Saved ##")

17 | P a g e
elif choice == 2:
query = "SELECT * FROM employee"
[Link](query)

result = [Link]()

print("%10s %20s %15s %10s" % ("EMPNO", "NAME", "DEPARTMENT", "SALARY"))

for row in result:


print("%10s %20s %15s %10s" % (row[0], row[1], row[2], row[3]))

elif choice == 0:
[Link]()
print("## Bye!! ##")

else:
print("## INVALID CHOICE ##")

OUTPUT:

1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice: 1

Enter Employee Number: 1


Enter Name: AMIT
Enter Department: SALES
Enter Salary: 9000
## Data Saved ##

Enter Choice: 1
Enter Employee Number: 2
Enter Name: NITIN
Enter Department: IT
Enter Salary: 80000
## Data Saved ##

Enter Choice: 2
EMPNO NAME DEPARTMENT SALARY
1 AMIT SALES 9000
2 NITIN IT 80000

Enter Choice: 0

18 | P a g e
13. Connect with database and update employee record of given empno

# Program to update employee record using MySQL


import [Link] as mycon
con = [Link](
host='[Link]',
user='root',
password="admin",
database="company"
)
cur = [Link]()
print("#" * 40)
print("EMPLOYEE UPDATION FORM")
print("#" * 40)
print()
ans = 'y'
while [Link]() == 'y':
eno = int(input("ENTER EMPNO TO UPDATE: "))
query = "SELECT * FROM employee WHERE empno = {}".format(eno)
[Link](query)
result = [Link]()
if [Link] == 0:
print("Sorry! Empno not found")
else:
print("%10s %20s %15s %10s" % ("EMPNO", "NAME", "DEPARTMENT", "SALARY"))
for row in result:
print("%10s %20s %15s %10s" % (row[0], row[1], row[2], row[3]))
choice = input("\n## ARE YOU SURE TO UPDATE? (Y): ")
if [Link]() == 'y':
print("== YOU CAN UPDATE ONLY DEPT AND SALARY ==")
print("== FOR EMPNO AND NAME CONTACT ADMIN ==")

d = input("ENTER NEW DEPARTMENT (leave blank to keep same): ")


if d == "":
d = row[2]
try:
s_input = input("ENTER NEW SALARY (leave blank to keep same): ")
if s_input == "":
s = row[3]
else:
s = int(s_input)
except:
s = row[3]

19 | P a g e
query = "UPDATE employee SET dept='{}', salary={} WHERE empno={}".format(d, s, eno)
[Link](query)
[Link]()

print("## RECORD UPDATED ##")

ans = input("UPDATE MORE (Y): ")

[Link]()

OUTPUT:

########################################
EMPLOYEE UPDATION FORM
########################################

ENTER EMPNO TO UPDATE: 2


EMPNO NAME DEPARTMENT SALARY
2 NITIN IT 90000

## ARE YOU SURE TO UPDATE? (Y): y


== YOU CAN UPDATE ONLY DEPT AND SALARY ==
== FOR EMPNO AND NAME CONTACT ADMIN ==

ENTER NEW DEPARTMENT (leave blank to keep same): SALES


ENTER NEW SALARY (leave blank to keep same):

## RECORD UPDATED ##

UPDATE MORE (Y): y

ENTER EMPNO TO UPDATE: 2


EMPNO NAME DEPARTMENT SALARY
2 NITIN SALES 90000

## ARE YOU SURE TO UPDATE? (Y): y

ENTER NEW DEPARTMENT (leave blank to keep same):


ENTER NEW SALARY (leave blank to keep same): 91000

## RECORD UPDATED ##

UPDATE MORE (Y): n

20 | P a g e
14. Connect with database and delete record of given employee number

# Program to delete employee record using MySQL


import [Link] as mycon

con = [Link](
host='[Link]',
user='root',
password="admin",
database="company"
)

cur = [Link]()

print("#" * 40)
print("EMPLOYEE DELETION FORM")
print("#" * 40)
print()

ans = 'y'

while [Link]() == 'y':


eno = int(input("ENTER EMPNO TO DELETE: "))

query = "SELECT * FROM employee WHERE empno = {}".format(eno)


[Link](query)
result = [Link]()

if [Link] == 0:
print("Sorry! Empno not found")
else:
print("%10s %20s %15s %10s" % ("EMPNO", "NAME", "DEPARTMENT", "SALARY"))

for row in result:


print("%10s %20s %15s %10s" % (row[0], row[1], row[2], row[3]))

choice = input("\n## ARE YOU SURE TO DELETE? (Y): ")

if [Link]() == 'y':
query = "DELETE FROM employee WHERE empno = {}".format(eno)
[Link](query)
[Link]()

print("=== RECORD DELETED SUCCESSFULLY! ===")

21 | P a g e
ans = input("DELETE MORE ? (Y): ")

[Link]()

OUTPUT:

########################################
EMPLOYEE DELETION FORM
########################################

ENTER EMPNO TO DELETE: 2


EMPNO NAME DEPARTMENT SALARY
2 NITIN SALES 91000

## ARE YOU SURE TO DELETE? (Y): y


=== RECORD DELETED SUCCESSFULLY! ===

DELETE MORE ? (Y): y

ENTER EMPNO TO DELETE: 2


Sorry! Empno not found

DELETE MORE ? (Y): n

22 | P a g e
15. Create a Student table and insert data. Then implement the following SQL commands:

1. Use ALTER TABLE to:


o Add a new attribute
o Modify data type
o Drop an attribute
2. Use UPDATE to modify data
3. Use ORDER BY to display data in ascending and descending order
4. Use DELETE to remove tuple(s)
5. Use GROUP BY and find:
o MIN
o MAX
o SUM
o COUNT
o AVG

CREATE TABLE Student (


RollNo INT PRIMARY KEY,
Name VARCHAR(20),
Class VARCHAR(10),
Marks INT
);

INSERT INTO Student VALUES


(1, 'Amit', 'XII', 85),
(2, 'Nitin', 'XII', 90),
(3, 'Riya', 'XII', 78),
(4, 'Sonal', 'XII', 88),
(5, 'Rahul', 'XII', 95);

ALTER TABLE Student ADD Age INT;

ALTER TABLE Student MODIFY Name VARCHAR(30);

ALTER TABLE Student DROP Age;

UPDATE Student
SET Marks = 92
WHERE RollNo = 3;

SELECT * FROM Student


ORDER BY Marks ASC;

SELECT * FROM Student


ORDER BY Marks DESC;

23 | P a g e
DELETE FROM Student
WHERE RollNo = 5;

SELECT Class,
MIN(Marks) AS Min_Marks,
MAX(Marks) AS Max_Marks,
SUM(Marks) AS Total_Marks,
COUNT(*) AS Total_Students,
AVG(Marks) AS Average_Marks
FROM Student
GROUP BY Class;

24 | P a g e

You might also like