DIVYANKA
DIVYANKA
PRACTICAL FILE
ROLL NO. :
NAME : Divyanka Mehlawat
CLASS : XII SCIENCE
SUBJECT : Computer Science
SUBJECT CODE : 083
SUBJECT GUIDE : Mrs. Annu Singh PGT (CS)
ACKNOWLEDGEMENT
––
SESSION 2023-24
COMPUTER SCIENCE (SUBJECT CODE-083) PRACTICAL LIST
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.
6. Write SQL query to display all the records from table empl.
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:
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:
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)
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]
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("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("5. Quit")
if choice==1:
radius=int(input("enter radius:"))
elif choice==2:
radius=int(input("enter radius:"))
elif choice==3:
width=int(input("enter width:"))
length=int(input("enter length:"))
elif choice==4:
width=int(input("enter width:"))
length=int(input("enter length:"))
elif choice==5:
else:
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:-
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
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()
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]]
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()
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 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()
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
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 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 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
choice = None
while choice != 0:
print("1. ADD RECORD")
print("2. DISPLAY RECORD")
print("0. EXIT")
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 )
if d == "" :
d=row[2]
if s == '' :
s=row[3]
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])
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) :")