0% found this document useful (0 votes)
3 views

Computer Science Practical File XII (24-25)

The document contains a series of Python programs demonstrating various functionalities such as reading files, counting characters, manipulating binary files, and implementing data structures like stacks. It also includes SQL commands for creating and managing a student database, including data insertion, updates, and queries for statistical analysis. Each program is accompanied by sample input and output to illustrate its functionality.
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 views

Computer Science Practical File XII (24-25)

The document contains a series of Python programs demonstrating various functionalities such as reading files, counting characters, manipulating binary files, and implementing data structures like stacks. It also includes SQL commands for creating and managing a student database, including data insertion, updates, and queries for statistical analysis. Each program is accompanied by sample input and output to illustrate its functionality.
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
You are on page 1/ 17

Date : Experiment No: 1

Program 1: Read a text file line by line and display each word separated by a #.

#Program to read content of file line by line


#and display each word separated by '#'

f = open("file1.txt")

for line in f:
words = line.split()
for w in words:
print(w+'#',end='')
print()
f.close()

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#

Page : 1
Date : Experiment No: 2

Program 2: Read a text file and display the number of vowels/consonants/uppercase/


lowercase characters in the file.

f = open("file1.txt")
v=0
c=0
u=0
l=0
o=0
data = f.read()
vowels=['a','e','i','o','u']
for ch in data:
if ch.isalpha():
if ch.lower() in vowels:
v+=1
else:
c+=1
if ch.isupper():
u+=1
elif ch.islower():
l+=1
elif ch!=' ' and ch!='\n':
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)
f.close()
NOTE : if the original content of file is:
India is my country I
love python
Python learning is fun 123@

OUTPUT
Total Vowels in file : 16
Total Consonants in file n : 30
Total Capital letters in file :2
Total Small letters in file : 44
Total Other than letters :4

Page : 2
Date : Experiment No: 3

Program 3: Remove all the lines that contain the character 'a' in a file and write it to another
file.

#Program to read line from file and write it to another line


#Except for those line which contains letter 'a'

f1 = open("file2.txt")
f2 = open("file2copy.txt","w")

for line in f1:


if 'a' not in line:
f2.write(line)
print(“## File Copied Successfully! ##”)
f1.close()
f2.close()

NOTE: Content of file2.txt


a quick brown fox
one two three four
five six seven
India is my country
eight nine ten
bye!

OUTPUT

## File Copied Successfully! ##

NOTE: After copy content of file2copy.txt


one two three fourfive six seven eight nine ten bye!

Page : 3
Date : Experiment No: 4

Program 4: 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
#creating the file and writing the data
f=open("records.dat", "wb")
pickle.dump(["Wakil", 1], f)
pickle.dump(["Tanish", 2], f)
pickle.dump(["Priyashi", 3], f)
pickle.dump(["Kanupriya", 4], f)
pickle.dump(["Aaheli", 5], f)
f.close()

#opeining the file to read contents


f=open("records.dat", "rb")
n=int(input("Enter the Roll Number: "))
flag = False
while True:
try:
x=pickle.load(f)
if x[1]==n:
print("Name: ", x[0])
flag = True
except EOFError:
break

if flag==False:
print("This Roll Number does not exist")

OUTPUT
Enter the Roll Number: 2
Name: Tanish

Enter the Roll Number: 6


This Roll Number does not exist
Page : 4
Date : Experiment No: 5

Program 5: Create a binary file with roll number, name and marks. Input a roll number and
update the marks.

import pickle
def Write():
f = open("Studentdetails.dat", 'wb')
while True:
r =int(input ("Enter Roll no : "))
n = input("Enter Name : ")
m = int(input ("Enter Marks : "))
record = [r,n,m]
pickle.dump(record,f)
ch = input("Do you want to enter more ?(Y/N)")
if ch in 'Nn':
break
f.close()
def Read():
f = open("Studentdetails.dat",'rb')
try:
while True:
rec=pickle.load(f)
print(rec)
except EOFError:
f.close()
def Update():
f = open("Studentdetails.dat", 'rb+')
rollno = int(input("Enter roll no whoes marks you want to update"))
try:
while True:
pos=f.tell()
rec = pickle.load(f)
if rec[0]==rollno:
um = int(input("Enter Update Marks:"))
rec[2]=um
f.seek(pos)
Page : 5
pickle.dump(rec,f)
#print(rec)
except EOFError:
f.close()
Write()
Read()
Update()
Read()

OUTPUT

Enter Roll no : 6
Enter Name : "Ramesh"
Enter Marks : 55
Do you want to enter more ?(Y/N)n
[6, '"Ramesh"', 55]
Enter roll no whoes marks you want to update6
Enter Update Marks:65
[6, '"Ramesh"', 65]

Page : 6
Date : Experiment No: 6

Program 6: Write a random number generator that generates random numbers between 1
and 6 (simulates a dice).

# Program to generate random number between 1 - 6 # To simulate the dice


import random
import time
print("Press CTRL+C to stop the dice ")
play='y'
while play=='y':
while True:
for i in range(10):
print()
n = random.randint(1,6)
print(n,end='')
time.sleep(.00001)
print("Your Number is :",n)
ans=input("Play More? (Y) :")
if ans.lower()!='y':
play='n'
break

OUTPUT

Your Number is : 4
Play More? (Y) :y
Your Number is : 3
Play More? (Y) :y
Your Number is : 2
Play More? (Y) :n

Page : 7
Date : Experiment No:7

Program 7: Write a Python program to implement a stack using list.

def isEmpty(S):
if len(S)==0:
return True
else:
return False

def Push(S,item):
S.append(item)
top=len(S)-1

def Pop(S):
if isEmpty(S):
return "Underflow"
else:
val = S.pop()
if len(S)==0:
top=None
else:
top=len(S)-1
return val

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

def Show(S):
if isEmpty(S):
print("Sorry No items in Stack ")
else:
t = len(S)-1
print("(Top)",end=' ')
while(t>=0):
print(S[t],"<==",end=' ') t-
=1
print()
Page : 8
begins here S=[]
#Stack
top=None
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:
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("\nDeleted 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

OUTPUT
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :1
Enter Item to Push :10

Cont…
Page : 9
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :1
Enter Item to Push :20

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


1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :1
Enter Item to Push :30

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


1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :4
(Top) 30 <== 20 <== 10 <==

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


1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :3 Top
Item : 30

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


1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :2

Deleted Item was : 30


Page : 10
**** STACK DEMONSTRATION ******
1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :4 (Top)
20 <== 10 <==

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


1. PUSH
2. POP
3. PEEK
4. SHOW STACK
0. EXIT
Enter your choice :0
Bye

Page : 11
Date : Experiment No: 8

Program 8: Write a Python program to implement a stack using list.

import csv

with open("user_info.csv", "w") as obj:

fileobj = csv.writer(obj)

fileobj.writerow(["User Id", "password"])

while(True):

user_id = input("enter id: ")

password = input("enter password: ")

record = [user_id, password]

fileobj.writerow(record)

x = input("press Y/y to continue and N/n to terminate the program\n")

if x in "Nn":

break

elif x in "Yy":

continue

with open("user_info.csv", "r") as obj2:

fileobj2 = csv.reader(obj2)

given = input("enter the user id to be searched\n")

for i in fileobj2:

next(fileobj2)
Page : 12
# print(i,given)

if i[0] == given:

print(i[1])

break

OUTPUT:

enter id: 15
enter password: "15121980"
press Y/y to continue and N/n to terminate the program
y
enter id: 16
enter password: "1512"
press Y/y to continue and N/n to terminate the program
n
enter the user id to be searched
15
"15121980"

Page : 13
Date : Experiment No: 9

Program 9: 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

CREATE DATABASE StudentDB;


USE StudentDB;
CREATE TABLE students (
roll_no INT NOT NULL,
age INT NOT NULL,
name VARCHAR(50) NOT NULL,
address VARCHAR(100) NOT NULL,
phone VARCHAR(20) NOT NULL,
PRIMARY KEY (roll_no)
);
INSERT INTO students (roll_no, age, name, address, phone)
VALUES
(1, 18, 'Shubham Thakur', '123 Main St, Mumbai', '9876543210'),
(2, 19, 'Aman Chopra', '456 Park Ave, Delhi', '9876543211'),
(3, 20, 'Naveen Tulasi', '789 Broadway, Ahmedabad', '9876543212'),
(4, 21, 'Aditya arpan', '246 5th Ave, Kolkata', '9876543213'),
(5, 22, 'Nishant Jain', '369 3rd St, Bengaluru', '9876543214')

SELECT * FROM Student;

Page : 14
ALTER TABLE Student ADD (COURSE varchar(40));
ALTER TABLE Student MODIFY COURSE varchar(20);

ALTER TABLE Student DROP COLUMN COURSE;

UPDATE student SET Address = ‘Lucknow’ WHERE name = ‘Abhishek’;


SELECT * FROM students ORDER BY ROLL_NO DESC;

Page : 15
SELECT * FROM students ORDER BY age DESC, name ASC;

DELETE FROM students WHERE name = 'Nishant Jain';

GROUP BY and find the min, max, sum, count and average

CREATE TABLE emp (


emp_no INT PRIMARY KEY,
name VARCHAR(50),
sal DECIMAL(10,2),
age INT
);
INSERT INTO emp (emp_no, name, sal, age) VALUES
(1, 'Aarav', 50000.00, 25),
(2, 'Aditi', 60000.50, 30),
(3, 'Aarav', 75000.75, 35),
(4, 'Anjali', 45000.25, 28),
(5, 'Chetan', 80000.00, 32),
(6, 'Divya', 65000.00, 27),
(7, 'Gaurav', 55000.50, 29),
(8, 'Divya', 72000.75, 31),
(9, 'Gaurav', 48000.25, 26),
(10, 'Divya', 83000.00, 33);

SELECT * from emp;

SELECT name, SUM(sal) FROM emp GROUP BY name;

SELECT * FROM emp WHERE sal>70000;


SELECT MIN(age) FROM student;
SELECT MAX(age) FROM student;
SELECT name, COUNT(name) FROM student;
SELECT AVG(sal) FROM student;

You might also like