12 Cs Python - Record Programs New 2024-25
12 Cs Python - Record Programs New 2024-25
12 Cs Python - Record Programs New 2024-25
Class: 12 PYTHON
1. Write a menu driven Python program to calculate and return the values of • Area of triangle •
Area of a circle • Area of regular polygon.
2.Write a menu driven program in Python using user defined functions to take a string as input and
• Check if it is palindrome • Count number of occurrences of a given character • Get an index from
user and replace the character at that index with user given value.
3.Write a menu driven program in Python using user defined functions that take a list as parameter
and return • maximum • minimum • sum of the elements
5. Write a menu driven program in Python using recursive function to perform linear and binary
search on a set of numbers. Compare the number of comparisons performed for a search.
6. Write a menu driven program in python to demonstrate the applications of random module
methods randint() and randrange().
7. Write a menu driven program in Python using user defined functions to implement Bubble sort
and selection sort technique.
8.Write a Python program i) to read a text file line by line and display each word separated by a ‘#’.
Ii) to remove all the lines that contain the character ‘a’ in a file and write it to another file.
9.Write a Python program to read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file.
10. Write a Python program to create a binary file with name and roll number and perform search
based on roll number.
11. Write a Python program to create a binary file with roll number, name and marks and
update the marks using their roll numbers.
12. Write a menu driven program in Python to create a CSV file with following data • Roll no •
Name of student • Mark in Sub1 • Mark in sub2 • Mark in sub3 • Mark in sub4 • Mark in sub5
Perform following operations on the CSV file after reading it. • Calculate total and percentage for
each student. • Display the name of student if in any subject marks are greater than 80% (Assume
marks are out of 100)
(1)
13. Take a sample of ten phishing e-mails (or any text file) and find most commonly
occurringword(s) using Python program.
14.Write a Python program to make user defined module and import same in another module or
program.
15. Write a menu driven program in Python to implement a stack using a list data structure. Each
node should have • Book no • Book name • Book price.
16. Write a menu driven program in Python to implement a queue using a list datastructure. Each
node should have • Item no • Item name • Item price
17.Write a Program to integrate SQL with Python by importing the MySQL module and
create a record of employee and display the record.
18.Write a Program to integrate SQL with Python by importing the MYSQL module to search an
employee number in table employee and display record, if empno not found display appropriate
message.
19. Write a Program to integrate SQL with Python by importing the MYSQL module to update the
employee record of entered empno.
20.Program to integrate SQL with Python by importing the MYSQL module to delete the record of
entered employee number.
(2)
1. Write a menu driven Python program to calculate and return the values of • Area of triangle •
Area of a circle • Area of regular polygon
# PROGRAM 2
import math
deftarea(b,h):
a = 0.5 * b * h
return a
defcarea(r):
a = math.pi * r *r
return a
defrarea(n,s):
a = (s * s * n) / ( 4 * math.tan(180/n))
return a
while(1):
print(" Menu")
print("1. Area of Triangle")
print("2. Area of Circle")
print("3. Area of Regular polygon")
print("4. Exit")
ch = int(input("Enter your choice:"))
if(ch==1):
b = float(input("Enter the base of triangle : "))
h = float(input("Enter the height of triangle : "))
print("The area of triangle : ",tarea(b,h))
elif(ch==2):
r = float(input("Enter the radius of circle :"))
print("The area of circle :",carea(r))
elif (ch==3):
n= int(input("Enter the number of sides"))
s = float(input("Enter the dimension of side"))
print("The area of the polygon :",rarea(n,s))
elif(ch==4):
break
else:
print("Wrong Choice")
(3)
output:
Menu
1. Area of Triangle
2. Area of Circle
3. Area of Regular polygon
4. Exit
Enter your choice:1
Enter the base of triangle : 12
Enter the height of triangle : 10
The area of triangle : 60.0
Menu
1. Area of Triangle
2. Area of Circle
3. Area of Regular polygon
4. Exit
Enter your choice:2
Enter the radius of circle :7
The area of circle : 153.93804002589985
Menu
1. Area of Triangle
2. Area of Circle
3. Area of Regular polygon
4. Exit
Enter your choice:3
Enter the number of sides5
Enter the dimension of side5
The area of the polygon : 4.032013071234286
Menu
1. Area of Triangle
2. Area of Circle
3. Area of Regular polygon
4. Exit
Enter your choice:3
Enter the number of sides7
Enter the dimension of side6
The area of the polygon : 95.83525305237683
Menu
1. Area of Triangle
2. Area of Circle
3. Area of Regular polygon
4. Exit
Enter your choice:4
(4)
2.Write a menu driven program in Python using user defined functions to take a string as input and
• Check if it is palindrome • Count number of occurrences of a given character • Get an index from
user and replace the character at that index with user given value.
import math
def palindrome(s):
rev = s[::-1]
if(rev == s):
print("The string is palindrome")
else:
print("The string is not a palindrome")
defcountc(s,c):
c = s.count(c)
return c
defreplacec(s,i):
c = s[i]
nc = input("Enter the character to replace :")
if(len(nc)==1):
ns = s.replace(c,nc)
print(ns)
return ns
else:
print("Enter only one character")
while(1):
print(" Menu")
print("1. Palindrome")
print("2. Number of Occurrences")
print("3. Replace character")
print("4. Exit")
ch = int(input("Enter your choice:"))
if(ch==1):
s = input("Enter the string :")
palindrome(s)
elif(ch==2):
s = input("Enter the string :")
c = input("Enter a character :")
if(len(c)==1):
print("The character ",c," is in ",s, ",", countc(s,c), " times")
else:
print("Enter only one character")
elif (ch==3):
s = input("Enter the string :")
i = int(input("Enter an index :"))
print("The string after replacement is :",replacec(s,i))
elif(ch==4):
break
else:
print("Wrong Choice")
(5)
Menu
1. Palindrome
2. Number of Occurrences
3. Replace character
4. Exit
Enter your choice:1
Enter the string :MALAYALAM
The string is palindrome
Menu
1. Palindrome
2. Number of Occurrences
3. Replace character
4. Exit
Enter your choice:2
Enter the string :Your limitation—it’s only your imagination.
Enter a character :l
The character l is in Your limitation—it’s only your imagination. , 2 times
Menu
1. Palindrome
2. Number of Occurrences
3. Replace character
4. Exit
Enter your choice:3
Enter the string :Dream it. Wish it. Do it.
Enter an index :8
Enter the character to replace :#
Dream it# Wish it# Do it#
The string after replacement is : Dream it# Wish it# Do it#
Menu
1. Palindrome
2. Number of Occurrences
3. Replace character
4. Exit
Enter your choice:4
(6)
3. Write a menu driven program in Python using user defined functions that take a list as parameter
and return • maximum • minimum • sum of the elements
# PROGRAM
def maximum(l):
m = l[0]
fori in range(len(l)):
if(l[i]>m):
m=l[i]
return m
def minimum(l):
m = l[0]
fori in range(len(l)):
if(l[i]<m):
m=l[i]
return m
defsuml(l):
s=0
fori in range(len(l)):
s = s + l[i]
return s
while(1):
print(" Menu")
print("1. Maximum of list")
print("2. Minimum of list")
print("3. Sum of list")
print("4. Exit")
ch = int(input("Enter your choice:"))
if(ch==1):
l = list(map(int,input("\nEnter the numbers : ").strip().split()))
m = maximum(l)
print("Maximum of given list elements is :",m)
elif(ch==2):
l = list(map(int,input("\nEnter the numbers : ").strip().split()))
m = minimum(l)
print("Minimum of given list elements is :",m)
elif (ch==3):
l = list(map(int,input("\nEnter the numbers : ").strip().split()))
s = suml(l)
print("Sum of given list elements is :",s)
elif(ch==4):
break
else:
print("Wrong Choice")
(7)
Menu
1. Maximum of list
2. Minimum of list
3. Sum of list
4. Exit
Enter your choice:1
(8)
4. Write a menu driven program in Python using recursive function to
• Display factorial of a number
• Find sum of first n natural numbers
• Display n terms of Fibonacci series
• Sum of digits of a number
# PROGRAM
def fact(n):
if(n<2):
return 1
else:
return n * fact(n-1)
defsumn(n):
if (n==1):
return 1
else:
return n + sumn(n-1)
deffibo(n):
if(n==1):
return 0
elif(n==2)or(n==3):
return 1
else:
returnfibo(n-1)+fibo(n-2)
defsumd(n):
if(n==0):
return 0
else:
d = n%10
n=n//10
return d + sumd(n)
while(1):
print('''menu
1. Factorial of a number
2. Sum of n natural numbers
3. Fibonacci Series
4. Sum of digits of a number
5. Exit''')
ch=int(input('enter choice'))
if (ch==1):
(9)
n = int(input("Enter the number : "))
if(n>=0):
print("The factorial of the number is : ",fact(n))
else:
print("The factorial of negative number is not defined")
elif (ch==2):
n = int(input("Enter the number : "))
print("The sum of natural numbers upto ",n," is ",sumn(n))
elif (ch==3):
n = int(input("Enter the number of terms : "))
print("The Fibonacci Series is:")
fori in range(1,n-1):
x = fibo(i)
print(x)
elif (ch==4):
n = int(input("Enter the number : "))
print("The sum of digits is :",sumd(n))
elif (ch==5):
break
else:
print('invalid input')
(10)
menu
1. Factorial of a number
2. Sum of n natural numbers
3. Fibonacci Series
4. Sum of digits of a number
5. Exit
enter choice1
Enter the number : 12
The factorial of the number is : 479001600
menu
1. Factorial of a number
2. Sum of n natural numbers
3. Fibonacci Series
4. Sum of digits of a number
5. Exit
enter choice2
Enter the number : 8
The sum of natural numbers upto 8 is 36
menu
1. Factorial of a number
2. Sum of n natural numbers
3. Fibonacci Series
4. Sum of digits of a number
5. Exit
enter choice3
Enter the number of terms : 10
The Fibonacci Series is:
0
1
1
2
3
5
8
13
menu
1. Factorial of a number
2. Sum of n natural numbers
3. Fibonacci Series
4. Sum of digits of a number
5. Exit
enter choice4
Enter the number : 16545
The sum of digits is : 21
(11)
5. Write a menu driven program in Python using recursive function to perform linear and binary
search on a set of numbers. Compare the number of comparisons performed for a search.
# PROGRAM
defbsearch(arr,ele,s,e):
if s <= e:
mid = (e + s) // 2
ifarr[mid] == ele:
return mid
elifarr[mid] >ele:
returnbsearch(arr, ele,s, mid-1)
else:
returnbsearch(arr, ele, mid + 1, e)
else:
return -1
deflsearch(arr,l,r,x):
if r < l:
return -1
ifarr[l] == x:
return l
ifarr[r] == x:
return r
returnlsearch(arr, l+1, r-1, x)
while(1):
print('''menu
1. Linear Search
2. Binary Search
3. Exit''')
ch=int(input('enter choice'))
if (ch==1):
l = list(map(int,input("Enter the elements of list :").strip().split()))
ele = int(input("Enter the element to search"))
res = lsearch(l,0,len(l)-1,ele)
(12)
if(res == -1):
print("The element not found")
else:
print("The element found at ",res)
elif (ch==2):
l = list(map(int,input("Enter the elements of list :").strip().split()))
ele = int(input("Enter the element to search"))
l.sort()
print(l)
res = bsearch(l,ele,0,len(l)-1)
if(res == -1):
print("The element not found")
else:
print("The element found at ",res)
elif (ch==3):
break
else:
print('invalid input')
(13)
menu
1. Linear Search
2. Binary Search
3. Exit
enter choice1
Enter the elements of list :45 67 78 23
Enter the element to search23
The element found at 3
menu
1. Linear Search
2. Binary Search
3. Exit
enter choice2
Enter the elements of list :20 30 40 50 60 70
Enter the element to search40
[20, 30, 40, 50, 60, 70]
The element found at 2
menu
1. Linear Search
2. Binary Search
3. Exit
enter choice2
Enter the elements of list :34 56 23 10
Enter the element to search30
[10, 23, 34, 56]
The element not found
menu
1. Linear Search
2. Binary Search
3. Exit
enter choice3
(14)
6. Write a menu driven program in python to demonstrate the applications of random module
methods randint() and randrange().
defrandomlist():
randomlist = []
fori in range(0,5):
n = random.randint(1,30)
randomlist.append(n)
print(randomlist)
defrandrangeapp():
print ("Random number from 0-100 is : ",end="")
print (random.randrange(100))
#_main_
print("You rolled a", roll())
# Continuing to roll the dice if user permits else quit
rolling = True
while rolling:
cont = input("Do we continue ? q – Quit ")
ifcont.lower() != "q":
print("You rolled a", roll())
else:
rolling = False
print("Thanks for Playing")
print(“random list”)
randomlist()
print(“randrange function”)
randrangeapp()
(15)
output:
You rolled a 6
Do we continue ? q – Quit 1
You rolled a 6
Do we continue ? q – Quit 5
You rolled a 5
Do we continue ? q – Quit 3
You rolled a 1
Do we continue ? q – Quit q
Thanks for Playing
random list
[13]
[13, 16]
[13, 16, 22]
[13, 16, 22, 30]
[13, 16, 22, 30, 20]
randrange function
Random number from 0-100 is : 46
(16)
7. Write a menu driven program in Python using user defined functions to implement Bubble sort
and selection sort technique.
defbubbleSort(nlist):
forpassnuminrange(len(nlist)-1,0,-1):
foriinrange(passnum):
ifnlist[i]>nlist[i+1]:
temp=nlist[i]
nlist[i]=nlist[i+1]
nlist[i+1]= temp
defselection_sort(input_list):
foridx in range(len(input_list)):
min_idx = idx
for j in range( idx +1, len(input_list)):
ifinput_list[min_idx] >input_list[j]:
min_idx = j
# Swap the minimum value with the compared value
nlist=[14,46,43,27,57,41,45,21,70]
bubbleSort(nlist)
print(“sorted list- bubble sort”)
print(nlist)
l = [19,2,31,45,30,11,121,27]
selection_sort(l)
print(“sorted list- selection sort”)
print(l)
output:
(17)
8.Write a Python program i) to read a text file line by line and display each word
separated by a ‘#’. Ii) to remove all the lines that contain the character ‘a’ in a file and
write it to another file.
Program:
defreada():
file=open("AI.TXT",")
lines=file.readlines()
for line in lines:
words=line.split() for
word in words:
print(word+"#",end=””)
print("")
file.close()
deftransfera():
file=open("C:\\Users\\Rec\\format.txt","r")
lines=file.readlines()
file.close() file=open("C:\\Users\\Rec\\
format.txt","w") file1=open("C:\\Users\\Rec\\
second.txt","w")
for line in lines:
if 'a' in line or 'A' in line:
file1.write(line)
else:
file.write(line)
print("Lines containing char 'a' has been removed from format.txt file")
print("Lines containing char 'a' has been saved in second.txt file")
file.close()
file1.close()
reada();
transfera();
(18)
output:
AI#
is#
an#
interdisciplinary#
science#
with#
multiple#
approaches.#
Smart#
assistants#
(like#
Siri#
and#
Alexa)#
Lines containing char 'a' has been removed from old.txt file
Lines containing char 'a' has been saved in second.txt file
(19)
9.Write a Python program to read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file
Program:
file=open("AI.TXT","r")
content=file.read()
forch in content:
if(ch.islower()):
lower_case_letter=1
elif(ch.isupper()):
upper_case_letter=1
ch=ch.lower()
if (ch in ['a','e','i','o','u']):
vowels+=1
elif(ch in ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']):
consonants+=1
file.close()
print("Vowels are :",vowels)
print("Consonants:",consonans)
print("Lower_case_letters :",lower_case_letters)
print("Upper_case_letters :",upper_case_letters)
Output:
Vowels are : 33
Consonants: 50
Lower_case_letters : 78
Upper_case_letters : 5
(20)
10. Write a Python program to create a binary file with name and roll number and perform
search based on roll number.
Program:
#Create a binary file with name and roll number
import pickle
stud_data={}
list_of_students=[]
no_of_students=int(input("Enter no of Students:")) for i
in range(no_of_students):
stud_data["roll_no"]=int(input("Enter roll no:"))
stud_data["name"]=input("Enter name: ")
list_of_students.append(stud_data)
stud_data={} file=open("StudDtl.dat","wb")
pickle.dump(list_of_students,file) print("Data
added successfully") file.close()
#Search for a given roll number and display the name, if not found display appropriate
message.”
import pickle file=open("StudDtl.dat","rb")
list_of_students=pickle.load(file)
roll_no=int(input("Enter roll no.of student to search:"))
found=False
forstud_data in list_of_students:
if(stud_data["roll_no"]==roll_no):
found=True print(stud_data["name"],"found in
file.")
if (found==False):
print("No student data found. please try again")
file.close()
(21)
Output:
Enter no of Students:3
(22)
11. Write a Python program to create a binary file with roll number, name and marks and
update the marks using their roll numbers.
Program:
#Create a binary file with roll number, name and marks.
import pickle
student_data={}
no_of_students=int(input("Enter no of Students to insert in file : "))
file=open("StudData","wb")
fori in range(no_of_students):
student_data["RollNo"]=int(input("Enter roll no :"))
student_data["Name"]=input("Enter Student Name :")
student_data["Marks"]=float(input("Enter Students Marks :"))
pickle.dump(student_data,file)
student_data={}
file.close()
print("data inserted Successfully")
(23)
exceptEOFError:
if(found==False):
print("Roll no not found") else:
print("Students marks updated Successfully")
file.close()
# print the updated data
import pickle
student_data={}
file=open("StudData","rb")
try:
while True: student_data=pickle.load(file)
print(student_data)
exceptEOFError:
file.close()
Output:
(24)
{'RollNo': 4, 'Name': 'Jagath', 'Marks': 84.0}
{'RollNo': 5, 'Name': 'Rishi', 'Marks': 92.0}
(25)
12. Write a menu driven program in Python to create a CSV file with following data • Roll no
• Name of student • Mark in Sub1 • Mark in sub2 • Mark in sub3 • Mark in sub4 • Mark in
sub5 Perform following operations on the CSV file after reading it. • Calculate total and
percentage for each student. • Display the name of student if in any subject marks are
greater than 80% (Assume marks are out of 100)
# PROGRAM
import csv
defwritefile(file):
l=[]
writer = csv.writer(file)
r = int(input("Enter the roll no :"))
n = input("Enter the name :")
s1 = int(input("Enter the marks for Subject 1 "))
s2 = int(input("Enter the marks for Subject 2 "))
s3 = int(input("Enter the marks for Subject 3 "))
s4 = int(input("Enter the marks for Subject 4 "))
s5 = int(input("Enter the marks for Subject 5 "))
data = [r,n,s1,s2,s3,s4,s5]
writer.writerow(data)
defreadfile(file):
reader = csv.reader(file)
for r in reader:
print("Roll no: ",r[0])
print("Name :",r[1])
fori in range(2,7):
print("Subject ",i-1,"marks :",r[i])
total = 0
fori in range(2,7):
total = total + int(r[i])
print ("Total : ",total)
print("Percentage : ", total/5)
(26)
def read90(file):
reader = csv.reader(file)
for r in reader:
flag = 0
fori in range(2,7):
if(int(r[i])>90):
flag = 1
if(flag==1):
print("Roll no: ",r[0])
print("Name :",r[1])
fori in range(2,7):
print("Subject",i-1,"marks :",r[i])
file = open("travel.csv","a+")
writer = csv.writer(file)
writer.writerow(["Roll No", "Name", "Sub1", "Sub2", "Sub3", "Sub4" , "Sub5"])
file.close()
while(1):
print('''menu
1. Write to CSV file
2. Display the total and percentage
3. Display students who scored above 90 in a subject
4. Exit''')
ch=int(input('enter choice'))
if (ch==1):
file = open("student.csv","a+",newline='')
writefile(file)
file.close()
elif (ch==2):
file = open("student.csv","r")
(27)
file.seek(0,0)
readfile(file)
file.close()
elif (ch==3):
file = open("student.csv","r")
file.seek(0,0)
read90(file)
file.close()
elif (ch==4):
break
else:
print('invalid input')
(28)
output:
menu
1. Write to CSV file
2. Display the total and percentage
3. Display students who scored above 90
4. Exit
enter choice1
Enter the roll no :1201
Enter the name :Swetha
Enter the marks for Subject 1 90
Enter the marks for Subject 2 78
Enter the marks for Subject 3 96
Enter the marks for Subject 4 80
Enter the marks for Subject 5 86
menu
1. Write to CSV file
2. Display the total and percentage
3. Display students who scored above 90
4. Exit
enter choice1
Enter the roll no :1202
Enter the name :Tara
Enter the marks for Subject 1 70
Enter the marks for Subject 2 80
Enter the marks for Subject 3 85
Enter the marks for Subject 4 82
Enter the marks for Subject 5 60
(29)
menu
1. Write to CSV file
2. Display the total and percentage
3. Display students who scored above 90
4. Exit
enter choice2
Roll no: 1201
Name :Swetha
Subject 1 marks : 90
Subject 2 marks : 78
Subject 3 marks : 96
Subject 4 marks : 80
Subject 5 marks : 86
Total : 430
Percentage : 86.0
Roll no: 1202
Name : Tara
Subject 1 marks : 70
Subject 2 marks : 80
Subject 3 marks : 85
Subject 4 marks : 82
Subject 5 marks : 60
Total : 377
Percentage : 75.4
menu
1. Write to CSV file
2. Display the total and percentage
3. Display students who scored above 90
4. Exit
(30)
enter choice3
Roll no: 1201
Name :Swetha
Subject 1 marks : 90
Subject 2 marks : 78
Subject 3 marks : 96
Subject 4 marks : 80
Subject 5 marks : 86
menu
1. Write to CSV file
2. Display the total and percentage
3. Display students who scored above 90
4. Exit
enter choice
(31)
13. Take a sample of ten phishing e-mails (or any text file) and find most commonly
occurring word(s) using Python program.
file=open("email.txt","r")
content=file.read()
max=0
max_occuring_word=""
occurances_dict={}
words=content.split()
count=content.count(word)
occurances_dict.update({word:count})
if(count>max):
max=count
max_occuring_word=word
print(occurances_dict)
Output:
(32)
14.Write a Python program to make user defined module and import same in another
module or program.
Program:
#Area_square.py
#code to calculate Area of Square
defSquare():
area=number*number
print("Area of Square:",area)
#Area_square.py
defRectangle():
area=l*b
#import package
#import package.py
importusermodule
print(Area_square.square())
print(Area_rect.Rectangle())
Output:
(33)
15. Write a menu driven program in Python to implement a stack using a list datastructure.
Each node should have • Book no • Book name • Book price
# PROGRAM
s = []
def push():
b_ID=int(input('enter book no.'))
b_NAME=input('enter book name')
b_PRICE=float(input('enter price'))
data=b_ID,b_NAME,b_PRICE
s.append(data)
print("Book added to stack")
def pop():
iflen(s)==0:
print('Stack is empty')
else:
dn = s.pop()
print(dn)
defdisp():
iflen(s)==0:
print('empty stack')
else:
fori in range(len(s)):
print("Book Id :",s[i][0])
print("Book Name :",s[i][1])
print("Book Price :",s[i][2])
while(1):
print('''menu
1. Push
2. Pop
3. Display
4. Exit''')
(34)
ch=int(input('enter choice'))
if (ch==1):
push()
elif (ch==2):
pop()
elif(ch==3):
disp()
elif (ch==4):
break
else:
print('invalid input')
output:
menu
1. Push
2. Pop
3. Display
4. Exit
enter choice1
enter book no.1
enter book nameIntroduction to Algorithms
enter price600
Book added to stack
menu
1. Push
2. Pop
3. Display
4. Exit
(35)
enter choice1
enter book no.2
enter book nameProgramming Pearls
enter price800
Book added to stack
menu
1. Push
2. Pop
3. Display
4. Exit
enter choice3
Book Id : 1
Book Name : Introduction to Algorithms
Book Price : 600.0
Book Id : 2
Book Name : Programming Pearls
Book Price : 800.0
menu
1. Push
2. Pop
3. Display
4. Exit
enter choice2
(2, ‘Programming Pearls ', 800.0)
(36)
16. Write a menu driven program in Python to implement a queue using a list datastructure.
Each node should have • Item no • Item name • Item price
# PROGRAM
q = []
def insert():
it_ID=int(input('Enter item no.'))
it_NAME=input('Enter item name')
it_PRICE=float(input('Enter item price'))
data=it_ID,it_NAME,it_PRICE
q.append(data)
print("Item added to queue")
def delete():
iflen(q)==0:
print('Queue is empty')
else:
dn = q.pop(0)
print(dn)
defdisp():
iflen(q)==0:
print('empty queue')
else:
fori in range(len(q)):
print("Item Id :",q[i][0])
print("Item Name :",q[i][1])
print("Item Price :",q[i][2])
while(1):
print('''menu
1. Insert
2. Delete
3. Display
4. Exit''')
(37)
ch=int(input('enter choice'))
if (ch==1):
insert()
elif (ch==2):
delete()
elif(ch==3):
disp()
elif (ch==4):
break
else:
print('invalid input')
output:
menu
1. Insert
2. Delete
3. Display
4. Exit
enter choice1
Enter item no.75
Enter item namePen
Enter item price50
Item added to queue
menu
1. Insert
2. Delete
3. Display
4. Exit
enter choice3
Item Id : 75
Item Name : Pen
(38)
Item Price : 50.0
menu
1. Insert
2. Delete
3. Display
4. Exit
enter choice2
(75, 'Pen', 50.0)
menu
1. Insert
2. Delete
3. Display
4. Exit
enter choice4
(39)
17.Write a Program to integrate SQL with Python by importing the MySQL
module and create a record of employee and display the record.
Program:
importmysql.connector
con=mysql.connector.connect(host="localhost",user='root',password="1234",
database="employee")
cur=con.cursor()
cur.execute("Create table EMPLOYEE(EMPNOint, NAME varchar(10), DEPARTMENT
cur=con.cursor()
while True:
DEPARTMENT=input(“Enter department:”)
{})".format(Empno,Name,Department,salary)
cur.execute(query)
con.commit()
print("row inserted successfully...")
ch=input("Do You Want to enter more records?(y/n)")
ifch=="n":
break
cur.execute("select * from employee")
data=cur.fetchall()
fori in data:
print(i)
print("Total number of rows retrieved=",cur.rowcount)
(40)
output:
(41)
18.Write a Program to integrate SQL with Python by importing the MYSQL module to search
an employee number in table employee and display record, if empno not found display
appropriate message.
Program:
importmysql.connector as mycon
con = mycon.connect(host='localhost',user='root',password="1234",
database="svvv")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE SEARCHING FORM")
print("#"*40)
print("\n\n")
ans='y'
whileans.lower()=='y':
eno = int(input("ENTER EMPNO TO SEARCH :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
ifcur.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 :1
EMPNO NAME DEPARTMENT SALARY
1 Krish Accounts 40000.0
(42)
19. Write a Program to integrate SQL with Python by importing the MYSQL module to
update the employee record of entered empno.
Program:
importmysql.connector as mycon
con = mycon.connect(host='localhost',user='root',password="1234", database="svvv")
cur = con.cursor()
print("#"*40)
cur.execute(query)
result = cur.fetchall()
ifcur.rowcount==0:
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])
ifchoice.lower()=='y':
(43)
try:
except:
s=row[3]
query="update employee set name='{}',department='{}',salary={} where
empno={}".format(n,d,s,eno)
cur.execute(query)
con.commit()
print("## RECORD UPDATED ## ")
ans=input("Do you want to update more? (Y) “)
OUTPUT:
########################################
EMPLOYEE UPDATION FORM
########################################
(44)
20.Program to integrate SQL with Python by importing the MYSQL module to delete the
record of entered employee number.
Program:
importmysql.connector as mycon
con = mycon.connect(host='localhost',user='root',password="1234", database="svvv")
cur = con.cursor()
print("#"*40)
print("EMPLOYEE DELETION FORM")
print("#"*40)
print("\n\n")
ans='y'
whileans.lower()=='y':
eno = int(input("ENTER EMPNO TO DELETE :"))
query="select * from employee where empno={}".format(eno) cur.execute(query)
result = cur.fetchall()
ifcur.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) :")
ifchoice.lower()=='y':
query="delete from employee where empno={}".format(eno)
cur.execute(query)
con.commit()
print("=== RECORD DELETED SUCCESSFULLY! ===")
ans=input("DELETE MORE ? (Y) :")
Output:
########################################
EMPLOYEE DELETION FORM
########################################
(45)