Practical File_23_24 (1)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

Submitted to: submitted by:

Mr. Pramod sharma RISHI KUMAR


Pgt computer science CLASS:- 12th A
Roll no. __________
PRACTICAL FILE (2024-25)
INDEX

Exp.
Aim Date Sign
No
Program to read and display file content line by
1
line with each word separated by “ #”
Program to read the content of file and display
2 the totalnumber of consonants, uppercase,
vowels and lowercase characters.
Program to read the content of file line by line
3 and write it to another file except for the lines
contains “a” letter in it.
Program to store students’ details like admission
number, roll number, name and percentage in a
4
dictionary and display information on the basis of
admission number.
Program to create binary file to store Roll no and
5 Name, Search any Roll no and display name if Roll no
found otherwise “Roll no not found”
6 Program to create binary file to store Roll no, Name
and Marks and update marks of entered Roll no.
7 Program to generate random number 1-6, simulating a
dice.
8 Program to implement Stack in Python using List.
Create a CSV file by entering user-id and password,
9 read and search the password for given user- id.
To write SQL-Queries for the following Questions
10
based on the given table
To write SQL-Queries for the following Questions
11
based on the given table
To write Queries for the following Questions based on
12
the given two table
Program to connect with database and store record of
13
employee and display records.
Program to connect with database and search
employee number in table employee and display
14
record, if empno not found display appropriate
message
Perform all the operations (Insert, Update, Delete,
15 Display) with reference to table ‘students’ through
MySQL-Python connectivity
Program 1: Program to read and display file content line by line with eachword
separated by “#”

#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()

India is my countryI lovepython


Python learning is fun

OUTPUT

============= RESTART: D:\Raval\Pr_1.py ============


India#is#my#
countryI#love#python#
Python#learning#is#fun#
>>>
Program 2: Program to read the content of file and display the total number of
consonants, uppercase, vowels and lower case characters.

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 :",c)
print("Total Capital letters in file :",u)
print("Total Small letters in file :",l)
print("Total Other than letters :",o)
f.close()

OUTPUT
============= RESTART: D:\Raval\Pr_2.py =======
Total Vowels in file : 16
Total Consonants in file : 30
Total Capital letters in file : 3
Total Small letters in file : 43
Total Other than letters : 0
>>>
Program 3: Program to read the content of file line by line and write it to another file
Except for the linescontains “a” letter in it.

f1 = open("file1.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 : if the original content of file1 is:

India is my countryI lovepython


Python learning is fun

OUTPUT
============= RESTART: D:\Raval\Pr_3.py =======
## File Copied Successfully! ##
>>>
Program 4:
Program to store student’s details like admission number, roll number, name and percentage in a
dictionary and display information on the basis of admission number.

record = dict ()
i=1
n= int (input ("How many records u want to enter: "))
while(i<=n):
Adm = input("Enter Admission number: ")
roll = input("Enter Roll Number: ")
name = input("Enter Name :")
perc = float(input("Enter Percentage : "))
t = (roll,name, perc)
record[Adm] = t
i= i+1
Nkey = record.keys()
for i in Nkey:
print("\nAdmno- ", i, " :")
r = record[i]
print("Roll No\t", "Name\t", "Percentage\t")
for j in r:
print(j, end = "\t")

OUTPUT
============= RESTART: D:\Raval\Pr_4.py =======
How many records u want to enter: 2
Enter Admission number: 101
Enter Roll Number: 38
Enter Name :Ramesh
Enter Percentage : 78
Enter Admission number: 102
Enter Roll Number: 39
Enter Name :Mahesh
Enter Percentage : 79

Admno- 101 :
Roll No Name Percentage
38 Ramesh 78.0
Admno- 102 :
Roll No Name Percentage
39 Mahesh 79.0
>>>
Program 5:
Program to create binary file to store Rollno and Name, Search any Rollno and display
name if Rollno found otherwise “Rollno not found”

import pickle
D={}
f=open("Studentdetails.dat","wb")
def write():
while True:
rno = int(input("Enter Roll no : "))
n = input("Enter Name : ")
D['Roll_No']=rno
D['Name'] = n
pickle.dump(D,f)
ch = input("More ? (Y/N)")
if ch in 'Nn':
break
f.close()
def Search() :
found = 0
rollno= int(input("Enter Roll no Whose name you want to display :"))
f = open("Studentdetails.dat", "rb")
try:
while True:
rec = pickle.load(f)
if rec['Roll No']==rollno:
print(rec['Name'])
found = 1
break
except EOFError:
if found == 0:
print("Sorry not Found. .. ")
f.close()
write()
Search()
OUTPUT
============= RESTART: D:\Raval\Pr_5.py =======

Enter Roll no : 1
Enter Name : Ramesh
More ? (Y/N)y
Enter Roll no : 2
Enter Name : Mahesh
More ? (Y/N)y
Enter Roll no Whose name you want todisplay :2
Mahesh
Program 6: Program to create binary file to store Rollno, Name and Marks
and update marks of entered Rollno.

#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
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)
pickle.dump(rec,f)
#print(rec)
except EOFError:
f.close()
Write()
Read()
Update()
Read()
OUTPUT
============= RESTART: D:\Raval\Pr_6.py =======

Enter Roll no : 1
Enter Name : ramesh
Enter Marks : 78
Do you want to enter more ?(Y/N)N
[1, 'ramesh', 78]
Enter roll no whoes marks you want to update1
Enter Update Marks:87
[1, 'ramesh', 87]
>>>
Program 7: Program to generate random number 1-6, simulating a dice.

# Program to generate random number between 1 -6


# tosimulate the dice

import random
while True:
print("="*55)
print("***********************Roling Dice****************************")
print("="*55)
num = random.randint(1,6)
if num ==6:
print("Hey.....You got",num,"....... Congratulations!!!!")
elif num ==1:
print("Well tried. ... But you got",num)
else:
print("You got:",num)
ch=input("Roll again? (Y/N)")
if ch in "Nn":
break
print("Thank for playing!!!!!!!!")

OUTPUT
============= RESTART: D:\Raval\Pr_7.py =======
=======================================================
***********************Roling Dice****************************
=======================================================
You got: 2
Roll again? (Y/N)y Thank for
playing!!!!!!!!
=======================================================
***********************Roling Dice****************************
=======================================================
Hey.....You got 6 ......Congratulations!!!!
Program 8 : Write a program to implement a stack for the employee
details (empno, name).

employee=[]
def push():
empno=input("Enter empno ")
name=input("Enter name ")
sal=input("Enter sal ")
emp=(empno,name,sal)
employee.append(emp)
def pop():
if(employee==[]):
print("Underflow / Employee Stack in empty")
else:
empno,name,sal=employee.pop()
print("poped element is ")
print("empno ",empno," name ",name," salary ",sal)
def traverse():
if not (employee==[]):
n=len(employee)
for i in range(n-1,-1,-1):
print(employee[i])
else:
print("Empty , No employee to display")
while True:
print("1. Push")
print("2. Pop")
print("3. Traversal")
print("4. Exit")
ch=int(input("Enter your choice "))
if(ch==1):
push()
elif(ch==2):
pop()
elif(ch==3):
traverse()
elif(ch==4):
print("End")
break
else:
print("Invalid choice")
OUTPUT
============= RESTART: D:\Raval\Pr_8.py =======

1. Push
2. Pop
3. Traversal
4. Exit
Enter your choice 1
Enter empno 101
Enter name Ramesh
Enter sal 34000
1. Push
2. Pop
3. Traversal
4. Exit
Enter your choice 3
('101', 'Ramesh', '34000')
1. Push
2. Pop
3. Traversal
4. Exit
Enter your choice
Program 9: Create a CSV file by entering user-id and password, read and
search the password for given user- id.

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)
# print(i,given)
if i[0] == given:
print(i[1])
break

OUTPUT
============= RESTART: D:\Raval\Pr_9.py =======

enter id: 101


enter password: 12345
press Y/y to continue and N/n to terminate the program
N
enter the user id to be searched
101
12345
>>>
SQL
queries
Program 10: To write SQL- Queries for the following Questions based on the
given table:

Rollno Name Gender Age Dept DOA Fees


1 Arun M 24 COMPUTER 1997-01-10 120
2 Ankit M 21 HISTORY 1998-03-24 200
3 Anu F 20 HINDI 1996-12-12 300
4 Bala M 19 NULL 1999-07-01 400
5 Charan M 18 HINDI 1997-09-05 250
6 Deepa F 19 HISTORY 1997-06-27 300
7 Dinesh M 22 COMPUTER 1997-02-25 210
8 Usha F 23 NULL 1997-07-31 200

(a) Write a Query to Create a new database in the name of "STUDENTS"


Sol:mysql> CREATE DATABASE STUDENTS;

(b) Write a Query to Open the database "STUDENTS"


Sol:mysql> USE STUDENTS;
(c) Write a Query to create the above table called: Info
Sol:
mysql> CREATE TABLE STU(Rollno int Primary key,Name varchar(10),Gender
varchar(3),Age int,Dept varchar(15),DOA date,Fees int);

(d) Write a Query to list all the existing database names.


Sol:
mysql> SHOW DATABASES;

(e) Write a Query to List all the tables that exists in the current database.
Sol:
mysql> SHOW TABLES;
Output:
(f) Write a Query to insert all the rows of above table into Info table.
Sol:
INSERT INTO STU VALUES (1,'Arun','M', 24,'COMPUTER','1997-01-10', 120);INSERT
INTO STU VALUES (2,'Ankit','M', 21,'HISTORY','1998-03-24', 200);
INSERT INTO STU VALUES (3,'Anu','F', 20,'HINDI','1996-12-12', 300);
INSERT INTO STU VALUES (4,'Bala','M', 19, NULL,'1999-07-01', 400);
INSERT INTO STU VALUES (5,'Charan','M', 18,'HINDI','1997-06-27', 250);
INSERT INTO STU VALUES (6,'Deepa','F', 19,'HISTORY','1997-06-27', 300);
INSERT INTO STU VALUES (7,'Dinesh','M', 22,'COMPUTER','1997-02-25', 210);
INSERT INTO STU VALUES (8,'Usha','F', 23, NULL,'1997-07-31', 200);

(g) Write a Query to display all the details of the Employees from the above table 'STU'.

Sol:

mysql> SELECT * FROM STU;

Output:

(h) Write a query to Rollno, Name and Department of the students from STU
table.
Sol:
mysql> SELECT ROLLNO,NAME,DEPT FROM STU;
Program 11: To write SQL- Queries for the following Questions based on the
given table:

Rollno Name Gender Age Dept DOA Fees


1 Arun M 24 COMPUTER 1997-01-10 120
2 Ankit M 21 HISTORY 1998-03-24 200
3 Anu F 20 HINDI 1996-12-12 300
4 Bala M 19 NULL 1999-07-01 400
5 Charan M 18 HINDI 1997-09-05 250
6 Deepa F 19 HISTORY 1997-06-27 300
7 Dinesh M 22 COMPUTER 1997-02-25 210
8 Usha F 23 NULL 1997-07-31 200

(a) Write a Query to delete the details of Roll number is 8.


Sol:

mysql> DELETE FROM STU WHERE ROLLNO=8;

Output (After Deletion):

(b) Write a Query to change the fess of Student to 170 whose Roll number is 1, if the existing
fessis less than 130.
Sol:

mysql> UPDATE STU SET FEES=170 WHERE ROLLNO=1 AND


FEES<130;

Output(After Update):
(c) Write a Query to add a new column Area of type varchar in table STU.

Sol:
mysql> ALTER TABLE STU ADD AREA VARCHAR(20);
Output:

(d) Write a Query to Display Name of all students whose Area Contains NULL.

Sol:
mysql> SELECT NAME FROM STU WHERE AREA IS NULL;

Output:

(e) Write a Query to delete Area Column from the table STU.

Sol:
mysql> ALTER TABLE STU DROP AREA;
Output:

(f) Write a Query to delete table from Database.


Sol:
mysql> DROP TABLE STU;
Output:
Program 12: To write Queries for the following Questions based on the
given two table:
TABLE: STOCK
Pno Pname Dcode Qty UnitPrice StockDate
5005 Ball point pen 102 100 10 2021-03-31
5003 Gel pen premium 102 150 15 2021-01-01
5002 Pencil 101 125 4 2021-02-18
5006 Scale 101 200 6 2020-01-01
5001 Eraser 102 210 3 2020-03-19
5004 Sharpner 102 60 5 2020-12-09
5009 Gel pen classic 103 160 8 2022-01-19

TABLE: DEALERS
Dcode Dname
101 Sakthi Stationeries
103 Classic Stationeries
102 Indian Book House

(a) To display the total Unit price of all the products whose Dcode as 102.

Sol:
mysql> SELECT SUM(UNITPRICE) FROM STOCK GROUP BY DCODE
HAVINGDCODE=102;
Output:

(b) To display details of all products in the stock table in descending order of Stock date.

Sol:
mysql> SELECT * FROM STOCK ORDER BY STOCKDATE DESC;

Output:
(c) To display maximum unit price of products for each dealer individually as
per dcodefrom the table Stock.

Sol:

mysql> SELECT DCODE,MAX(UNITPRICE) FROM STOCK


GROUP BY DCODE;
Output:

(d) To display the Pname and Dname from table stock and dealers.

Sol:
mysql> SELECT PNAME,DNAME FROM STOCK S,DEALERS D
WHERE S.DCODE=D.DCODE;

Output:
Python
Database
Connectivity
Program 13: Program to connect with database and store record of employee and display
records.

import mysql.connector as mycon


con = mycon.connect(host='localhost',
user='root',
password="root")
cur = con.cursor()
cur.execute("create database if not exists company")
cur.execute("use company")
cur.execute("create table if not exists employee(empno int, name varchar(20), dept varchar(20),salary int)")
con.commit()
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)
cur.execute(query)
con.commit()
print("## Data Saved ##")
elif choice == 2:
query="select * from employee"
cur.execute(query)
result = cur.fetchall()
print("%10s"%"EMPNO","%20s"%"NAME","%15s"%"DEPARTMENT", "%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
elif choice==0:
con.close()
print("## Bye!! ##")
OUTPUT:

1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :1
Enter Employee Number :101
Enter Name :RAMESH
Enter Department :IT
Enter Salary :34000
## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :2
EMPNO NAME DEPARTMENT SALARY
101 RAMESH IT 34000
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice : 0
Program 14: Program to connect with database and search employee number in table
employee and display record, if empno not found display appropriate message.

import mysql.connector as mycon


con = mycon.connect(host='localhost',
user='root',
password="root",
database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE SEARCHING FORM")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO SEARCH :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO", "%20s"%"NAME","%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
ans=input("SEARCH MORE (Y) :")

OUTPUT:
########################################
EMPLOYEE SEARCHING FORM
########################################

ENTER EMPNO TO SEARCH :101


EMPNO NAME DEPARTMENT SALARY
101 RAMESH IT 34000
SEARCH MORE (Y) :
Program 15: Perform all the operations (Insert, Update, Delete, Display) with reference to table
‘student’ through MySQL-Python connectivity

import mysql.connector as ms
db=ms.connect(host="localhost",
user="root",
passwd="root",
database="class_xii"
)
#cn=db.cursor()
def insert_rec():
try:
while True:
rn=int(input("Enter roll number:"))
sname=input("Enter name:")
marks=float(input("Enter marks:"))
gr=input("Enter grade:")
cn.execute("insert into student values({},'{}',{},'{}')".format(rn,sname,marks,gr))
db.commit()
ch=input("Want more records? Press (N/n) to stop entry:")
if ch in 'Nn':
print("Record Inserted ")
break
except Exception as e:
print("Error", e)
def update_rec():
try:
rn=int(input("Enter rollno to update:"))
marks=float(input("Enter new marks:"))
gr=input("Enter Grade:")
cn.execute("update student set marks={},gr='{}' where rn={}".format(marks,gr,rn))
db.commit()
print("Record Updated .... ")
except Exception as e:
print("Error",e)
def delete_rec():
try:
rn=int(input("Enter rollno to delete:"))
cn.execute("delete from student where rn={}".format(rn))
db.commit()
print("Record Deleted ")
except Exception as e:
print("Error",e)

def view_rec():
try:
cn.execute("select * from student")
records = cn.fetchall()
for record in records:
print(record)
#db.commit()
#print("Record...")
except Exception as e:
print("Error",e)
db = ms.connect( host="localhost",
user="root",
passwd="root",
database="class_xii"
)
cn = db.cursor()
while True:
print("MENU\n1. Insert Record\n2. Update Record \n3. Delete Record\n4. Display Record \n5.Exit")
ch=int(input("Enter your choice<1-4>="))
if ch==1:
insert_rec()
elif ch==2:
update_rec()
elif ch==3:
delete_rec()
elif ch==4:
view_rec()
elif ch==5:
break
else:
print("Wrong option selected")
OUTPUT:

MENU
1. Insert Record
2. Update Record
3. Delete Record
4. Display Record
5.Exit
Enter your choice<1-4>=1
Enter roll number:101
Enter name:Ramesh
Enter marks:85
Enter grade:A
Want more records? Press (N/n) to stop entry:n
Record Inserted
MENU
1. Insert Record
2. Update Record
3. Delete Record
4. Display Record
5.Exit
Enter your choice<1-4>=4
(101, 'Ramesh', 85.0, 'A')
MENU
1. Insert Record
2. Update Record
3. Delete Record
4. Display Record
5.Exit
Enter your choice<1-4>=2
Enter rollno to update:101
Enter new marks:58
Enter Grade:B
Record Updated....
MENU
1. Insert Record
2. Update Record
3. Delete Record
4. Display Record
5.Exit
Enter your choice<1-4>=4
(101, 'Ramesh', 58.0, 'B')
MENU
1. Insert Record
2. Update Record
3. Delete Record
4. Display Record
5.Exit
Enter your choice<1-4>=5

You might also like