0% found this document useful (0 votes)
48 views79 pages

DIVYANKA

Uploaded by

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

DIVYANKA

Uploaded by

Nisha Mehlawat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 79

GREENWOOD PUBLIC SCHOOL

ACADEMIC YEAR: 2023-24

PRACTICAL FILE

ROLL NO. :
NAME : Divyanka Mehlawat
CLASS : XII SCIENCE
SUBJECT : Computer Science
SUBJECT CODE : 083
SUBJECT GUIDE : Mrs. Annu Singh PGT (CS)
ACKNOWLEDGEMENT

We would like to thank Mrs. Jyoti Sharma, Principal of Greenwood


Public School, Gurugram.
We are deeply indebted to our mentor Mrs. Annu Singh.
We further thank to all the staff members of Greenwood Public School,
Gurugram.
We owe our sincere gratitude towards Greenwood Public School.
Our heartful thanks to CBSE.
We also express our deepest gratitude to our parents.
Finally, we would like to wind up by paying our heartful thanks to all our
near and dear ones.

GREENWOOD PUBLIC SCHOOL (CBSE), SECTOR-9, GURUGRAM

––
SESSION 2023-24
COMPUTER SCIENCE (SUBJECT CODE-083) PRACTICAL LIST

Functions and Data File Handling Python Programs


SL PRACTICAL DATE TEACHER’S
NO. NAME SIGNATURE
1. Write a program to store student”s information in a dictionary
and
display the information on the basis of admission number.
2. Write a program to check whether a string starts with specified
characters.
3. Write a menu driven program for a Student Management
System.
4. Write a program to enter the names of employees and their
salary
as input and store them in dictionary.
5. Write a program to accept string as an input and to count and
display the total number of times character is present.
6. Write a program to pass a dictionary to a function with list of
elements as keys and frequency of occurrence as value and
return as dictionary.
7. Write a function listchange(Arr) in python, which accepts a list
Arr of numbers, the function will replace the even number by
value 10
and multiply odd numbers by 5.
8. Write a program to make a chain of functions of decorators
(bold,
italics, underline, etc.) in python.
9. Write a user defined function findname(name) where name is an
argument in python to delete phone number from a
dictionary phonebook on the basis of the name, where
name is the key.
10. Write a program in python that calculates the following
* Area of the circle
* Circumference of the circle
* Area of the rectangle
* Perimeter of a rectangle
11. Write a program to find roots of a quadratic function.

12. Write a method in python to find and display the prime numbers
between 2 to N. Pass N as an argument to the method.
13. Write a program with a user defined function with string as a
parameter which replaces all vowels in the string with ‘*’.
14. Write a program using a user defined function to accept these
details for all students of your school and display them.
15. Write a function to create copy of file “test_report.txt”
named as “file1.txt” which should convert the first letter of
the file and the
first alphabetic character following a full stop into uppercase.
16. Write a program to store and display multiple integers in binary
.
SL PRACTICAL NAME DATE TEACHER’S
NO. SIGNATURE
17. Write a program to read byte by byte from a file using seek()
and tell().
18. Write a menu driven to perform all basic operations in
student binary file such as inserting, updating, reading,
searching etc. in python.
19. Write a program to write data onto “students” CSV file using
writerows() method.
20. Write a program to write data onto “students” CSV file using
writerows() method. (Modification of above program)
21. Write a program to compute the Total salary of the employee
and also calculate the size of the binary file.
22. Write a program that copies a text file barring the lines
starting with a “@” sign.
23. Write a menu-driven program to perform read and write
operations using a text file.
24. Write a function in python to count the number of lines in a
text file which are starting with the alphabet ‘A’.
25. Write a program in python to insert records in g_meet.dat
binary file until user presses ‘n’. The information is Google
meeting id, Google meeting time and class.
26. Write a user-defined program to input data for a record and
add to ‘book.dat’ and also write a function in python which
accepts the Author name as a parameter and count and return
the number of books by the given author.
27. Write a menu-driven program implementing user-defined
functions to perform different functions on a csv file
“student”.
28. Write a program to add the records of new books in a file so
that the records are stored for future retrieval and can be
accessed whenever required.
29. Develop a python program which stores data in
“employee.csv”, calculates and display total salary remitted
to its employee and to display the number of employees who
are getting salary of more than 5000 per month.
30. Write a function countRec() in python that would read
content of the file “STUDENT.DAT” and display the details
of those students whose percentage is above 75%.
SL PRACTICAL NAME DATE TEACHER’S
NO. SIGNATURE
1. Write a program to create a stack called Employee to
perform some basic operations using list.
SL PRACTICAL NAME DATE TEACHER’S
NO. SIGNATURE
2. Write a program to implement a stack for these book-
details(book no, book name). That is, now each item node of
the stack contains two type of information- a book no. and its
name. Just implement PUSH and display operations.
3. Write a menu-based program to add, delete and display the
record of the hostel using list as a data structure in python.
4. Write a program constituting methods in python to add,
display and remove a name from a given Stack of names of
countries.
5. Write a program to connect with database and store record of
employees and display records.
6. Write a program to connect with database and update the
employee record of entered empno.
7. Write a program to connect with database and search
employee number in table employee and display record , if
empno not found display appropriate message.
8. Write a program to connect with database and delete the
employee record of entered empno.

SQL QUERIES PROGRAMS

SL PRACTICAL NAME DATE TEACHER’S


NO. SIGNATURE
1. Write SQL query to create a database Employee.

2. Write SQL query to open database Employee.

3. Write SQL query to create following Table name empl.

4. Write SQL query to show the structure of table.

5. Write SQL query to insert 10 records same as it is in image.

6. Write SQL query to display all the records from table empl.

7. Write SQL query to display EmpNo and EName of all


employees from the table empl.
8. Write SQL query to display EName, Sal and Sal added with
comm from table empl.
SL PRACTICAL NAME DATE TEACHER’S
NO. SIGNATURE
9. Write SQL query to display EName, Sal and deptno who are
not getting commission from table empl.
10. Write SQL query to display EName, Sal and Sal*12 as
Annual Salary whose commission is not NULLfrom table.
11. Write SQL query to display the details of emloyees whose
name have only 4 letters.
12. Write SQL query to display name, job title and salary of
employee who do not have manager.
13. Write SQL query to display the name of the employee whose
name contains “A” as 3rd letter.
14. Write SQL query to display the name of the departments.
Each department should be displayed once(DISTINCT)
15. Write SQL query to display the name and salary of those
employees whose salary is between 35000 and 40000.
(BETWEEN)
16. Write SQL query to display tables data according to
ascending order of sal.
17. Write SQL query to change EName MITA by MIRA.

18. Write SQL query to delete records whose deptno=10

19. Write SQL query to add a new column Phno.

20. Write SQL query to delete entire table IF EXISTING.

21. Queries for Aggregate functions- SUM( ), AVG( ), MIN( ),


MAX( ), COUNT()
22. TEXT FUNCTIONS ( TRIM FUNCTION, SUBSTR
FUNCTION, LEFT FUNCTION, RIGHT FUNCTION ,
MID FUNCTION)
23. MATH FUNCTIONS ( POWER(), ROUND(), MOD() ).

24. DATE FUNCTIONS NOW(), DATE(), MONTH(),


MONTHNAME(), YEAR(), DAY(), DAYNAME()
25. Querying and manipulating data using Group by, Having,
Order by.
26. Create a table DEPT and show Cartesian Product, JOIN
(Cartesian Join, Equi Join, Natural Join)
Program 1:- Write a program to store students information in a dictionary and
display the information on the basis of admission number.
Source Code:

scl=dict()
i=1
flag=0
n = int(input("Enter the number of entries: "))
while i <=n:
adm = int(input("Enter admission number: "))
name = input("Enter student name: ")
section = input("Enter class and section: ")
percentage = float(input("Enter percentage obtained: "))b=(name,section,percentage)
scl[adm]=b
i=i+1
l=scl.keys()
for i in l:
print(adm- i)
z=scl[i]
print("Name\t", "Class\t", "Percentage\t")
for j in z:
print(j, end="\t")

OUTPUT
Program 2:- Write a program to check whether a string starts with specified
characters.
Source Code:

def caesar_encrypt (realText,step):


outText=[]
cryptText=[]
uppercase=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q',
'R','S','T','U','V','W','X','Y','Z']

lowercase=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y',
'z']
for eachLetter in realText:
if eachLetter in uppercase:
index=uppercase.index(eachLetter)
crypting=(index+step)%26
cryptText.append(crypting)
newLetter=uppercase[crypting]
outText.append(newLetter)
elif eachLetter in lowercase:
index=lowercase.index(eachLetter)
crypting=(index+step)%26
cryptText.append(crypting)
newLetter=lowercase[crypting]
outText.append(newLetter)
return outText
code=caesar_encrypt('abc',2)
print()
print(code)
print()

OUTPUT
Program 3:- Write a program to enter the names of employees and their salary as
input and store them in dictionary.
Source Code:

num=int(input("enter the no of employees whose data is to be


stored:")) count=1
employee=dict()
while
count<=num:
name=input("enter the name of the
employees:") salary=(int(input("enter the
salary:"))) employee[name]=salary
count+=1
print("\n\nEMPLOYEE_NAME\t:-\t\tSALARY:")
for k in employee:
print(k, '\t\t\t\t',employee[k])

OUTPUT
Program 4:- Write a menu driven program for a Student Management System.
SOURCE CODE:

marksList = [82, 74, 86, 98, 83, 77, 90, 80, 95, 68]
choice = 0
while True:
print ("The list marksList contains the marks of",len (marksList), "students as:",
marksList)

print ("\n STUDENT MANAGEMENT SYSTEM")


print(" 1. Add marks of new students")

print (" 2. Insert the marks at the desired position")

print(" 3. Append list of new students to the given list")


print (" 4. Modify marks of existing student")

print (" 5. Delete marks for left students by its position")


print (" 6. Delete the marks of a left student by its value")

print(" 7. Sort the list of marks obtained in ascending order")


print(" 8. Sort the list of marks obtained in descending order")

print(" 9. Display the final marks list")

print(" 10. Exit")

choice= int (input ("ENTER YOUR CHOICE (1-10): "))


if choice == 1:
element=int (input ("Enter the marks to be added: "))
marksList.append(element)
print ("The marks have been appended\n")
elif choice ==2 :
element= int (input ("Enter the marks to be inserted:"))
pos =int (input ("Enter the positions:"))
marksList.insert(pos,element)
print("the marks have been inserted\n")
elif choice==3:
newlist =int (input ("Enter the list to be appended:"))
marksList.extend(newlist)
print("The list has been appended\n")
elif choice == 4:
i=int(input("Enter the position of the marks of student to be modified:"))
if i< len(marksList):
newmarks=int(input("enter the new marks:"))
oldmarks=marksList[i]
marksList[i]=newmarks
print("the previousmarks",oldmarks,"have been modified\n")
else:
print("position of the element is more than the lenth of the list")
elif choice==5:
i=int(input("enter the position of the marks of the student to be deleted:"))
if i<len(marksList):
element=marksList.pop(i)
print("the marks",element,"has been deleted\n")
else:
print("\npostion of the element is more than the length of list")
elif choice==6:
marks_element=int(input("\nenter the marks of the student to be deleted:"))
if marks_element in marksList:
marksList.remove(marks_element)
print("\nthe marks",marks_element,"has been deleted\n")
else:
print("\nrequested marks",marks_element,"is not present in the list")
elif choice==7:
marksList.sort()
print("\nthe list has been sorted in the asscending order")
elif choice==8:
marksList.sort(reverse=True)
print("\nthe list has been sorted in the descending order")
elif choice ==9:
print("\nthe final marks list is:",marksList)
elif choice==10:
break
else:
print("choice is not valid") print("\n\
npress any key to continue.........................")
ch=input()
Program 5:- Write a program to accept string as an input and to count and
display the total number of times character is present.

Source Code:

def countchar(str,chr):
str=input("enter any string:")
char=input("Enter character to count:")
count=0

for i in range(len(str)): if
(str[i]==char):
count+=1
print(count)
countchar(str,chr)

OUTPUT
Program 6:- Write a program to pass a dictionary to a function with list of
elements as keys and frequency of occurrence as value and return as dictionary.

Source Code:

def frequencyCount(list1,dict):
for i in list1:
if i not in dict:
dict[i]=1
else:
dict[i]+=1
return dict

list1=[4,8,6,5,10,6,5,5,40,30,7]

d={}
frequencyCount(list1,d)
print(d)

OUTPUT
Program 7:- Write a function listchange(Arr) in python, which accepts a list Arr of
numbers, the function will replace the even number by value 10 and multiply odd
numbers by 5.
Source Code:

def listchange(arr,n):

l=len(arr)

for a in range(l):

if(arr[a]%2==0):

arr[a]=10

else:

arr[a]=arr[a]*5

arr=[10,20,23,45]

n=int(input("enter number for n:"))

listchange(arr,n)

print(arr)

OUTPUT
Program 8:- Write a program to make a chain of functions of decorators (bold,
italics, underline, etc.) in python.

Source Code:-

def make_bold(fn):

def wrapped():

return"<b>"+fn()+"</b>"

return wrapped

def make_italic(fn):

def wrapped():

return"<i>"+fn()+"</i>"

return wrapped

def make_underline(fn):

def wrapped():

return"<u>"+fn()+"</u>"

return wrapped

@make_bold

@make_italic

@make_underline

def hello():

return"hello world"

print(hello())

OUTPUT
Program 9:- Write a user defined function findname(name) where name is an
argument in python to delete phone number from a dictionary phonebook on the
basis of the name, where name is the key.

Source Code:-
phonebook={"rahul":"12345678","amit":"0000000000","zayn":"909098989",

"rekha":"566657565"}

def findname(name):

if

phonebook.keys():del

phonebook[name]

else:

print("name not found")

print("Phonebook Information")

print("Name","\t","Phone Number")

for i in phonebook.keys():

print(i,'\t',phonebook[i])

name=input("enter name:")

findname(name)

OUTPUT
Program 10:- Write a program in python that calculates the following:-
* Area of the circle
* Circumference of the circle
* Area of the rectangle
* Perimeter of a rectangle
Source Code:-
CIRCLE MODULE:-
import math

def area(radius):

return math.pi*radius**2

def circumference(radius):

return 2*math.pi*radius

RECTANGLE MODULE:-
def area(width,length):

return width*length

def perimeter(width,length):

return 2*(width+length)

MAIN PROGRAM:-
import circle

import rectangle

choice=0

ch="y"

while (ch=="y"):

print("MENU")

print("1. Area of a circle")

print("2. Circumference of a circle")

print("3. Area of a rectangle")


print("4. Perimeter of a circle")

print("5. Quit")

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

if choice==1:

radius=int(input("enter radius:"))

print("the Area of circle is",circle.area(radius))

elif choice==2:

radius=int(input("enter radius:"))

print("the Circumference of circle is",circle.circumference(radius))

elif choice==3:

width=int(input("enter width:"))

length=int(input("enter length:"))

print("the area of rectangle is",rectangle.area(width,length))

elif choice==4:

width=int(input("enter width:"))

length=int(input("enter length:"))

print("the Perimeter of rectangle is",rectangle.perimeter(width,length))

elif choice==5:

print("exiting the program.............")

else:

print("ERROR: invalid selection")


OUTPUT
Program 11:- Write a program to find roots of a quadratic function.

Source Code:-
from math import sqrt
print ("quadratic equation is :(a*x^2)+b*x+c")
a=float(input("a: "))
b=float(input("b: "))
c=float(input("c: "))

r=b**2 - 4*a*c

if r>0:
num_root=2
x1=(((-b)+sqrt(r))/(2*a))
x2=(((-b)-sqrt(r))/(2*a))
print("the two root are: ",x1)
print("and",x2)
elif r==0:
num_root=1
x=(-b)/2*a
print("there is one root:",x)
else:
num_root=0
print("no roots, discriminant<0.")

OUTPUT
Program 12:- Write a method in python to find and display the prime
numbers between 2 to N. Pass N as an argument to the method.

Source Code:-

def check_primeAll (N) :


count = 0
for i in range(2, N + 1) :
count = 0
for j in range(2,i) :
if i % j == 0 :
count = 1
if count == 0 :
print(i)
N=int(input("enter any number:"))
check_primeAll(N)

output
Program 13:- Write a program with a user defined function with string as a
parameter which replaces all vowels in the string with ‘*’.
Source Code:-
def replaceVowel(st):
newstr=""
for character in st:
if character in "aeiou AEIOU":
newstr+="*"
else:
newstr+=character
return newstr
st=input("Enter a string:")
st1=replaceVowel(st)
print("The original string is:",st)
print("The modified string is:",st1)

OUTPUT
Program 14:- Write a program using a user defined function to accept
these details for all students of your school and display them.
Source Code:-

def personal_details():
name=input("Enter student name:")
roll=int(input("Enter the roll no.:"))
age=int(input("Enter the age:"))
Class=int(input("Enter student class:"))
address=input("Enter residential address:")
state=input("Enter the state:")
pincode=int(input("Enter address pincode:"))
print("t\t ABC Public School")
print("Name: {}\t\t Roll No: {}\nAge: {}\t\t\tClass: {}\nAddress: {}\tState:{}\
nPinCode: {}" format(name,roll,age,Class,address,state,pincode))
personal_details()
OUTPUT
Program 15:- Write a function to create copy of file “test_report.txt”
named as “file1.txt” which should convert the first letter of the file and
the first alphabetic character following a full stop into uppercase.
Source Code:-
def capitalize_sentence():
f1=open("test_report.txt",'r')
f2=open("file1.txt",'w')
while 1:
line=f1.readline()
if not line:
break
line=line.rstrip()
linelength=len(line)
str=""
str=str+line[0].upper()
i=1
while i<linelength:
if line[i]==".":
str=str+line[i]
i=i+1
if i>=linelength:
break

str=str+line[i].upper()
else:
str=str+line[i]
i=i+1
f2.write(str)
else:
print("source file
does not exist")
f1.close()
f2.close()
capitalize_sentence()
Program 16:- Write a program to store and display multiple integers in
binary.
Source Code:-

def binfile():
import pickle
file=open("data.dat","wb")
while True:
x=int(input("Enter the integer:"))
pickle.dump(x,file)
ans=input("Do you want to enter more data Y/N :")
if ans.upper()=="N":
break
file.close()
file=open("data.dat","rb")
try:
while True:
y=pickle.load(file)
print(y)
except EOFError:
pass
file.close()

binfile()

OUTPUT
Program 17:- Write a program to read byte by byte from a file using seek()
and tell().
Source Code:-

f=open("test.txt")
print("Before reading:",f.tell())
s=f.read()
print("After reading:",f.tell())
f.seek(0)
s=f.read(4)
print("First 4 bytes are:",s)
print(f.tell())
s=f.read(3)
print("First 3 bytes are:",s)
print(f.tell())
f.close()

OUTPUT
Program 18:-
Write a menu driven to perform all basic operations in student binary file
such as inserting, updating, reading, searching etc. in python.
Source Code:-
import os
import pickle

#Accepting data for dictionary


def insertRec():
rollno=int(input("Enter roll number:"))
name=input("Enter name:")
marks=int(input("Enter marks:"))
#creating the dictionary
rec={"Rollno": rollno,"Name": name,"Marks": marks}
#writing the dictionary
f=open("student.dat","ab")
pickle.dump(rec,f)
f.close()

#reading the records


def readRec():
f = open("student.dat","rb")
while True:
try:
rec=pickle.load(f)
print("Roll Num:",rec['Rollno'])
print("Name:",rec['Name'])
print("Marks:",rec['Marks'])
except EOFError:
break
f.close()
#searching for a record based on Rollno
def searchRollNo(r):
f=open("student.dat","rb")
flag=False
while True:
try:
rec=pickle.load(f)

if rec['Rollno']==r:
print("Roll Num:",rec['Rollno'])
print("Name:",rec['Name'])
print("Marks:",rec['Marks'])
flag=True
except EOFError:
break
if flag==False:
print("No record Found")
f.close()

#Marks modification for a RollNo


def updateMarks(r,m):
f=open("student.dat","rb")
reclst=[]
while True:
try:
rec=pickle.load(f)
reclst.append(rec)
except EOFError:
break
f.close()
for i in range(len(reclst)):
if reclst[i]['Rollno'] == r:
reclst[i]['Marks'] = m
f = open("student.dat",'wb')
for x in reclst:
pickle.dump(x,f)
f.close()

#deleting a record based on RollNo


def deleteRec(r):
f=open("student.dat","rb")
reclst=[]
while True:
try:
rec=pickle.load(f)
reclst.append(rec)
except EOFError:
break
f.close()
f=open("student.dat",'wb')
for x in reclst:
if x['Rollno'] == r:
continue
pickle.dump(x,f)
f.close()

while True:
print('Type 1 to insert rec.')
print('Type 2 to display rec.')
print('Type 3 to search rec.')
print('Type 4 to update rec.')
print('Type 5 to delete rec.')
print('Enter your choice 0 to exit')
choice=int(input("Enter your choice:"))
if choice==0:
break
elif
choice==1:
insertRec()
elif
choice==2:
readRec()
elif choice==3:
r=int(input("Enter a rollno.:"))
searchRollNo(r)
elif choice==4:
r=int(input("Enter a rollno.:"))
m=int(input("Enter new marks:"))
updateMarks(r,m)
elif choice==5:
r=int(input("Enter a rollno.:"))
deleteRec(r)
Program 19:- Write a program to write data onto “students” CSV file
using writerows() method.
Source Code:-

import csv

fields=['Name','Class','Year','Percent']

rows=[[Mohit,'XII',2015,96],
['Shaurya','XI',2016,72],
['Hardeep','XII',2017,90],
['Prerna','XI',2018,85],
['Lakshya','XII',2019,72]]

with open('marks.csv', 'w')


as file: writer =
csv.writer(file)
writer.writerow(fields)
# Use writerows() not
writerow()
writer.writerows(rows)
Program 20:- Write a program to write data onto “students” CSV file using
writerows() method. (Modification of above program)
Source Code:-

import csv

fields=['Name','Class','Year','Percent']

rows=[['Rohit','XII','2003','92'],
['Shaurya','XII','2004','82'],
['Deep','XII','2002','80'],
['Prerna','XI','20066','85'],
['Lakshya','Xii','2005','72']]

with open("newmarks.csv",'w',newline='')as f:
csv_w=csv.writer(f,delimiter=',')
csv_w.writerow(fields)
csv_w.writerows(rows)
print("All rows written in one go")
Program 21:- Write a program to compute the Total salary of the employee
and also calculate the size of the binary file.
Source Code:-

import pickle
print('working with binary files')
bfile=open("empfile.dat","ab")
recno=1
print("Enter records of employees")
print()
while True:
print("RECORD No.",recno)
eno=int(input("\tEmployee Number:"))
ename=input("\tEmployee Name:")
allow=int(input("\tAllowances:"))
ebasic=int(input("\tBasic salary:"))
totsal=ebasic+allow
print("\tTotal Salary:",totsal)
edata=[eno,ename,ebasic,allow,totsal]
pickle.dump(edata,bfile)
ans=input("Do you wish to enter more records(y/n)?")
recno=recno+1
if ans.lower()=='n':
print("Record entry OVER")
print()
break
print("Size of the binary file(in bytes):",bfile.tell())
bfile.close()
print("Now reading the employee records from the file")
print()
readrec=1
try:
with open("empfile.dat","rb") as bfile:
while True:
edata=pickle.load(bfile)
print("Record Number:",readrec)
print(edata)
readrec=readrec+1
except EOFError:
pass
bfile.close()
Program 22:-Write a program that copies a text file barring the lines
starting with a “@” sign.
Source Code:-
def filter(oldfile,newfile):
fin=open(oldfile,"r")
fout=open(newfile,"w")
while True:
text=fin.readline()
if len(text)==0:
break
if text[0]=="@":
continue
fout.write(text)
fin.close()
fout.close()
filter("source.txt","target.txt")
Program 23:- Write a menu-driven program to perform read and write
operations using a text file.
Source Code:-
import os
filename="student.txt"
def student_record(filename):
if not os.path.isfile(filename):
print("File not created")
else:
ch='y'
print("Enter student details:")
with open(filename,'a') as file1:
while ch=='Y' or ch=='y':
roll_no=input("Enter roll no:")
name=input("Enter name:")
address=input("enter address:")
file1.write(str(roll_no)+","+name.upper()+","+address+"\n")
file1.flush()
ch=input("Want to add more records:?<y/n>:")
if ch=="y" or ch=='y':
continue
else:
break
def student_readdata(filename):
if os.path.isfile(filename):
with open(filename) as file1:
print("-------------------------------------")
for student in file1:
print(student,end="")
else:
print("file does not exist")
def student_search(filename):
if os.path.isfile(filename):
with open(filename) as file1:
roll_no=int(input("enter roll no. to be searched:"))
flag = False
for student in file1:
str_len = len(student)
i=0
str_roll_no=""
while True:
if student[i] == ",":
break
if student[i]>'0' and student[i]<='9':
str_roll_no = str_roll_no + student[i]
i += 1
s_rollno=int(str_roll_no)
if roll_no==s_rollno:
print("Student found:",student,end="")
flag = True
break

def get_menu():
choice = int(input ("Select a choice (1-4):"))
return choice

def main():
print("Student's Menu:-\n1) Add new student record \n2) Display student details\n3)
Search student\n4) Save and Quit")
choice = get_menu()
while choice!=4:
if choice == 1:
student_record(filename)
elif choice == 2:
student_readdata(filename)
elif choice == 3:
student_search(filename)
else:
print ("Invalid choice, try again")
choice = get_menu()

if name ==" main ":


main()
Program 24:- Write a function in python to count the number of lines in a
text file which are starting with the alphabet ‘A’.
Source Code:-
def countlines():
file = open('hello.txt', 'r')
lines = file.readlines()
count = 0
for w in lines:
if w[0] == "A" or w[0] == "a":
count = count+1
print("Total lines:", count)
file.close()

countlines()
Program 25:- Write a program in python to insert records in g_meet.dat
binary file until user presses ‘n’. The information is Google meeting id,
Google meeting time and class.
Source Code:-
import pickle
f1 = open("g_meet.dat", "ab")
while True:
gmeet_id = input("Enter id: ")
gmeet_time = input("Enter time:")
gmeet_class = (input("Enter google meet class:"))
rec = {"Google Meeting id": gmeet_id, "Google Meet Time": gmeet_time, "Google
Meet Class": gmeet_class}
pickle.dump(rec, f1)
ch = input("Want more records: ")
ch = ch.lower()
if ch == 'n':
break
print('File created with data.')
f1.close()
Program 26:- Write a user-defined program to input data for a record and
add to ‘book.dat’ and also write a function in python which accepts the
Author name as a parameter and count and return the number of books by
the given author.
Source Code:-
import pickle

def createfile():
f = open("Book.dat", "ab")
bookNo = int(input("Book Number: "))
Book_name = input("Name :")
author = input("Author: ")
price = int(input("Price: "))
rec = [bookNo, Book_name, author, price]
pickle.dump(rec, f)
f.close()

def countrec(author):
with open('Book.dat', 'rb') as f:
num = 0
while True:
try:
rec = pickle.load(f)
if author ==
rec[2]: num = num
+1
a = num
print(a)
except EOFError as e:
pass
createfile()
auth = input('Enter Author name:')
countrec(auth)
Program 27:- Write a menu-driven program implementing user-
defined functions to perform different functions on a csv file “student”.
Source Code:-
# To create a CSV File by writing individual lines
import csv

def createcsv(): # Open CSV File


csv_f = open('student.csv', 'w', newline='')
# CSV object for writing
csv_w = csv.writer(csv_f)
while True:
Rno = int(input("Rno:"))
name = input("Name: ")
Marks = float(input("Marks: "))
fields = ['Roll_no', 'Name', 'Marks']
Lines = [Rno, name, Marks]
# Writing a line in CSV file
csv_w.writerow(fields)
csv_w.writerow(Lines)
print('Line recorded.')
csv_f.close()
break
# Closing a CSV File
# To create a CSV File by writing all lines in one go

def createcsv2():
# Open CSV File
csv_f = open('student.csv', 'a', newline='')
# CSV Object for writing
csv_w = csv.writer(csv_f)
Lines = []
while True:
Rno = int(input("Rno: "))
Name = input("Name: ")
Marks = float(input("Marks: "))
Lines.append([Rno, Name, Marks])
Ch = input("More (Y/N)?")
if Ch == 'N':
break
csv_w.writerows(Lines)
csv_f.close()

# Writing all lines in CSV file

# Closing a CSV File

# To read and show the content of a CSV File

def showall():
# Opening CSV File for reading
csv_f = open('student.csv', 'r', newline='')
# Reading the CSV content in object
csv_r = csv.reader(csv_f)
for Line in csv_r: # Extracting line by line content
print(Line)
csv_f.close()
# Closing a CSV File

print('CSV File Handling')

while True:
ch = input('1: Create CSV\n2: Create CSVALL\n3: Show CSV\n4: QUit\n-Enter
your choice:')
if ch == '1':
createcsv()
elif ch == '2':
createcsv2()
elif ch == '3':
showall()
else:
break
Program 28:- Write a program to add the records of new books in a file so
that the records are stored for future retrieval and can be accessed
whenever required.
Source Code:-
file1 = open('book.txt', 'a')
ch = 'y'
while ch == 'y':
book_id = int(input('Enter book number:'))
book_name = input('Enter book name:')
author = input('Enter author name:')
price = input('Enter price:')
book_rec = str(book_id) + ',' + book_name + ',' + author + ',' + str(price) + '\n'

file1.write(book_rec)
print('Book added')
ch = input('Want to add more record?:')
file1.close()
Program 29:- Develop a python program which stores data in
“employee.csv”, calculates and display total salary remitted to its employee
and to display the number of employees who are getting salary of more than
5000 per month.
Source Code:-
import csv
with open('employee.csv') as csv_f:
csv_r = csv.reader(csv_f, delimiter=',')
count = 0
sum = 0
print('Em_no', '\t\t', 'Em_name', '\t\t', 'Salary')
print('======================================================')
for rec in csv_r:
print(rec[0], '\t\t', rec[1], '\t\t', rec[2])
sum += int(rec[2])
if (int(rec[2])) > 5000:
count += 1
print('======================================================')
print('\t The sum of salaries of all employees:', sum)
print('Employee getting salary > 5000', count)
print('======================================================')
k
Program 30:- Write a function to write data into binary file marks.dat and
display the records of students who scored more than 95 marks.
Source Code:-
import pickle
def search_95plus():
f = open("marks.dat","ab")
while True:
rn=int(input("Enter the rollno:"))
sname=input("Enter the name:")
marks=int(input("Enter the marks:"))
rec=[]
data=[rn,sname,marks]
rec.append(data)
pickle.dump(rec,f)
ch=input("Wnat more records?Yes:")
if ch.lower() not in 'yes':
break
f.close()
f = open("marks.dat","rb")
cnt=0
try:
while True:
data = pickle.load(f)
for s in data:
if s[2]>95:
cnt+=1
print("Record:",cnt)
print("RollNO:",s[0])
print("Name:",s[1])
print("Marks:",s[2])
except Exception:
f.close()
search_95plus()
Stack and MySQL Codes
Program 1:- Write a program to create a stack called Employee to perform some
basic operations using list.

Source Code:-

s=[]
c="y"
while(c=="y"):
print("1. Push")
print("2. Pop")
print("3. Display")
choice=int(input("Enter your choice:"))
if (choice==1):
a=input("Enter employee no:")
ename=input("Enter the employee:")
l=[a,ename]
s.append(l)
elif (choice==2):
if (s==[]):
print("Stack empty")
else:
print("Delete element is : ",s.pop())
elif(choice==3):
i=len(s)
for i in range(i-1,-1,-1):
print(s[i-1])
else:
print("Wrong input")
c=input("Do you want to continue or not?(Y/N)")
Program 2:- Write a program to implement a stack for these book-
details(book no, book name). That is, now each item node of the stack
contains two type of information- a book no. and its name. Just implement
PUSH and display operations.
Source Code:-
def isempty(stk):
if stk==[]:
return True
else:
return False
def push(stk,item):
stk.append(item)
top=len(stk) -1

def display(stk):
if isempty(stk):
print("The Stack is Empty")
else:
top=len(stk) -1
print(stk[top],"top")
for a in range(top-1, -1, -1):
print(stk[a])

stack=[]
c='y'
top = None
while(c=="y"):
print("Stack Operation")
print("1 Push")
print("2 Display")
print("3 Exit")
ch=int(input("Enter your choice(1-3):"))
if ch==1:
bno=int(input("Enter Book no. to be inserted:"))
bname=input("Enter Book name to be inserted:")
item=[bno, bname]
push(stack, item)
elif ch==2:
display(stack)
elif ch==3:
break
else:
print("Invalid Choice!!!!!!")
input()
Program 3:- Write a menu-based program to add, delete and display the
record of the hostel using list as a data structure in python
Source Code:-

def push (host):


hn=int(input("enter hostel number:"))
ts=int(input("enter total student:"))
tr=int(input("enter total rooms:"))
temp=[hn,ts,tr]
host.append(temp)

def pop (host):


if (host==[]):
print("no record")
else:
print("deleted record is:", host.pop())

def display(host):
l=len(host)
print("hostel number\ttotal students\ttotal rooms")
for i in range(l-1,-1,-1):
print(host[i][0],"\t\t",host[i][1],"\t\t",host[i][2])

host=[]
ch='y'
ch=input("Do you want to enter (y/n):")
while(ch=='y' or ch=='n'):
print("1. Add record:")
print("2. Delete record:")
print("3. Display record:")
print("4. Exit:")
op=int(input("Enter the choice:"))
if (op==1):
push(host)
elif (op==2):
pop(host)
elif (op==3):
display(host)
elif (op==4):
break
Program 4:- Write a program constituting methods in python to add, display
and remove a name from a given Stack of names of countries.
Source Code:-
def push(country_name):
cname = input("enter the name of the country to be added.")
country_name.append(cname)

def pop (country_name):


if country_name !=[]:
print(country_name.pop())
else:
print("empty stack of encyclopedia")

def show(country_name):
print(country_name)

stack=[]
choice=''
while choice !='q':
print("p:push o:pop s:show q:quit")
choice= input ("Enter your choice:")
if choice == "p":
push(stack)
elif choice == "o":
pop(stack)
elif choice == "s":
show(stack)
elif choice == "q":
break
Program 5: Program to connect with database and store record of
employee and display records.
Source Code:-
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 employe(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 employe values({}, '{}', '{}', {})".format(e, n, d, s)
cur.execute(query)
con.commit()
print("## Data Saved ##")

elif choice == 2:
query = "select * from employe"
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])
con.close()
print("## Bye!! ##")
else:
print("## INVALID CHOICE ##")
Program 6: Program to connect with database and update the
employee record of entered empno.
Source Code:-
import mysql.connector as mycon
con = mycon.connect(host='localhost',user='root',password="Tritium!@#",
database="company")

cur = con.cursor()
print("#"*40)
print("EMPLOYEE UPDATION FORM")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO UPDATE :"))
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]
choice=input("\n## ARE YOUR SURE TO UPDATE ? (Y) :")

if choice.lower()=='y':
print("== YOU CAN UPDATE ONLY DEPT AND SALARY ==")
print("== FOR EMPNO AND NAME CONTACT ADMIN ==")
d = input("ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT
WANT TO CHANGE )

s = int(input("ENTER NEW SALARY,(LEAVE BLANK IF NOT


WANT TO CHANGE ) ")

if d == "" :
d=row[2]
if s == '' :
s=row[3]

cur.execute('update employee set dept = (%s), salary = (%s) where empno =


(%s)', (d, s, eno,))

con.commit()
Program7: Program to connect with database and search
employee number in table employee and display record, if empno
not found display appropriate message.
Source Code:-
import mysql.connector as mycon
con = mycon.connect(host='localhost',user='root',password="root"
database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEESEARCHINGFORM")
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) :")


Program 8: Program to connect with database and delete the
employee record of entered empno.
Source Code:-
import mysql.connector as mycon
con = mycon.connect(host='localhost',user='root',password="root",
database="company")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE DELETION FORM")
print("#"*40)
print("\n\n")
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO DELETE :")
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])
choice=input("\n## ARE YOUR SURE TO DELETE ? (Y) :")
if choice.lower()=='y':
query="delete from employee where empno={}".format(eno)
cur.execute(query)
con.commit()
print("=== RECORD DELETED SUCCESSFULLY! ===")
ans=input("DELETE MORE ? (Y) :")

You might also like