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

12 Cs Python - Record Programs With Output

Hi

Uploaded by

balasushim03
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

12 Cs Python - Record Programs With Output

Hi

Uploaded by

balasushim03
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

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

def tarea(b,h):
a = 0.5 * b * h
return a

def carea(r):
a = math.pi * r *r
return a

def rarea(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")
def countc(s,c):
c = s.count(c)
return c
def replacec(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]
for i in range(len(l)):
if(l[i]>m):
m=l[i]
return m
def minimum(l):
m = l[0]
for i in range(len(l)):
if(l[i]<m):
m=l[i]
return m
def suml(l):
s=0
for i 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

Enter the numbers : 56 67 89 23 14 48


Maximum of given list elements is : 89
Menu
1. Maximum of list
2. Minimum of list
3. Sum of list
4. Exit
Enter your choice:2

Enter the numbers : 34 76 90 35 19 40


Minimum of given list elements is : 19
Menu
1. Maximum of list
2. Minimum of list
3. Sum of list
4. Exit
Enter your choice:3

Enter the numbers : 45 56


Sum of given list elements is : 101

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

def sumn(n):
if (n==1):
return 1
else:
return n + sumn(n-1)

def fibo(n):
if(n==1):
return 0
elif(n==2)or(n==3):
return 1
else:
return fibo(n-1)+fibo(n-2)
def sumd(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:")
for i 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
def bsearch(arr,ele,s,e):
if s <= e:
mid = (e + s) // 2
if arr[mid] == ele:
return mid
elif arr[mid] > ele:
return bsearch(arr, ele,s, mid-1)
else:
return bsearch(arr, ele, mid + 1, e)
else:
return -1
def lsearch(arr,l,r,x):
if r < l:
return -1
if arr[l] == x:
return l
if arr[r] == x:
return r
return lsearch(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().

# Function to roll a dice( random numbers between 1 and 6 (simulates a dice)).


import random
def roll():
s=random.randint(1,6)
return s

# function to create list with random numbers

def randomlist():
randomlist = []
for i in range(0,5):
n = random.randint(1,30)
randomlist.append(n)
print(randomlist)

# functionUsing randrange() to generate numbers from 0-100

def randrangeapp():
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 ")
if cont.lower() != "q":
print("You rolled a", roll())
else:
rolling = False
print("Thanks for Playing")
print(“random list”)
randomlist()
print(“randrange function”)
randrangeapp()

output:

(15)
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.

# Python program for implementation of Bubble Sort

def bubbleSort(nlist):
for passnum in range(len(nlist)-1,0,-1):
for i in range(passnum):
if nlist[i]>nlist[i+1]:
temp = nlist[i]
nlist[i] = nlist[i+1]
nlist[i+1] = temp

# Python program for implementation of Selection Sort

def selection_sort(input_list):
for idx in range(len(input_list)):
min_idx = idx
for j in range( idx +1, len(input_list)):
if input_list[min_idx] > input_list[j]:
min_idx = j
# Swap the minimum value with the compared value

input_list[idx], input_list[min_idx] = input_list[min_idx], input_list[idx]

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:

sorted list- bubble sort


[14, 21, 27, 41, 43, 45, 46, 57, 70]
sorted list- selection sort
[2, 11, 19, 27, 30, 31, 45, 121]

(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:
def reada():
file=open("AI.TXT",")
lines=file.readlines()
for line in lines:
words=line.split()
for word in words:
print(word+"#",end=””)
print("")
file.close()
def transfera():
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();
output:

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

vowels=0 consonants=0 lower_case_letters=0 upper_case_letters=0

for ch 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:

(19)
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
for stud_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()

(20)
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")
for i 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")

#Input a roll number and update the marks.


import pickle
student_data={}
found=False
roll_no=int(input("Enter the roll no to update marks :"))
file=open("StudData","rb+")
try:
while True:
pos=file.tell()
student_data=pickle.load(file)
if(student_data["RollNo"]==roll_no):

student_data["Marks"]=float(input("Enter marks to update: "))


file.seek(pos)
pickle.dump(student_data,file)
found=True
except EOFError:
(21)
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)
except EOFError:
file.close()

Output:

Enter no of Students to insert in file : 5


Enter roll no :1
Enter Student Name :Anush
Enter Students Marks :90
Enter roll no :2
Enter Student Name :Bhavesh
Enter Students Marks :78
Enter roll no :3
Enter Student Name :Kiran
Enter Students Marks :95
Enter roll no :4
Enter Student Name :Jagath
Enter Students Marks :84
Enter roll no :5
Enter Student Name :Rishi
Enter Students Marks :92
data inserted Successfully
Enter the roll no to update marks :3
Enter marks to update: 85
Students marks updated Successfully
{'RollNo': 1, 'Name': 'Anush', 'Marks': 90.0}
{'RollNo': 2, 'Name': 'Bhavesh', 'Marks': 78.0}
{'RollNo': 3, 'Name': 'Kiran', 'Marks': 85.0}
{'RollNo': 4, 'Name': 'Jagath', 'Marks': 84.0}
{'RollNo': 5, 'Name': 'Rishi', 'Marks': 92.0}
(22)
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
def writefile(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)

def readfile(file):
reader = csv.reader(file)
for r in reader:
print("Roll no: ",r[0])
print("Name :",r[1])
for i in range(2,7):
print("Subject ",i-1,"marks :",r[i])
total = 0
for i in range(2,7):
total = total + int(r[i])
print ("Total : ",total)
print("Percentage : ", total/5)

(23)
def read90(file):
reader = csv.reader(file)
for r in reader:
flag = 0
for i in range(2,7):
if(int(r[i])>90):
flag = 1

if(flag==1):
print("Roll no: ",r[0])
print("Name :",r[1])
for i 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")

(24)
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')

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

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

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

(27)
13. Take a sample of ten phishing e-mails (or any text file) and find most commonly
occurringword(s) using Python program.

file=open("email.txt","r")

content=file.read()

max=0

max_occuring_word=""

occurances_dict={}

words=content.split()

for word in words:

count=content.count(word)

occurances_dict.update({word:count})

if(count>max):

max=count

max_occuring_word=word

print("Most occuring word is:",max_occuring_word)

print("No of times it occuredis:",max)

print("Other words frequency is:")

print(occurances_dict)

Output:

Most occuring word is: a


No of times it occured is: 8
Other words frequency is:
{'The': 1, 'difference': 1, 'between': 1, 'a': 8, 'successful': 1, 'person': 1, 'and': 1, 'others': 1,
'is': 1, 'not': 2, 'lack': 3, 'of': 3, 'strength.': 1, 'knowledge.': 1, 'but': 1, 'rather': 1, 'will.': 1}

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

def Square():

number=int(input("Enter the number:"))

area=number*number

print("Area of Square:",area)

#Area_square.py

#code to calculate Area of Rectangle

def Rectangle():

l=int(input("Enter the Length: "))

b=int(input("Enter the Breadth: "))

area=l*b

print("Area of Rectangle:" ,area)

#import package

#import package.py

import usermodule

from usermodule import Area_square,Area_rect

print(Area_square.square())

print(Area_rect.Rectangle())
Output:

Enter the number:7


Area of Square: 49
None
Enter the Length: 8
Enter the Breadth: 5
Area of Rectangle: 40
None

(29)
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():
if len(s)==0:
print('Stack is empty')
else:
dn = s.pop()
print(dn)
def disp():
if len(s)==0:
print('empty stack')
else:
for i 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''')

(30)
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 name Introduction to Algorithms
enter price600
Book added to stack
menu
1. Push
2. Pop
3. Display
4. Exit

(31)
enter choice1
enter book no.2
enter book name Programming 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)

(32)
16. Write a menu driven program in Python to implement a queue using a list data
structure. 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():
if len(q)==0:
print('Queue is empty')
else:
dn = q.pop(0)
print(dn)
def disp():
if len(q)==0:
print('empty queue')
else:
for i 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''')

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

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

(35)
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:
import mysql.connector
con=mysql.connector.connect(host="localhost",user='root',password="1234",

database="employee")
cur=con.cursor()
cur.execute("Create table EMPLOYEE(EMPNO int, NAME varchar(10), DEPARTMENT

varchar(20), SALARY float)")

print("table created successfully:")

cur=con.cursor()

while True:

EMPNO=int(input("Enter Employee Number :"))

Name=input("Enter Employee Name:")

DEPARTMENT=input(“Enter department:”)

salary=float(input("Enter Employee Salary:")),salary)

query="Insert into employee

values({},'{}',{})".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)")

if ch=="n":
break
cur.execute("select * from employee")

data=cur.fetchall()
for i in data:
print(i)
print("Total number of rows retrieved=",cur.rowcount)

(36)
output:

table created successfully:


Enter Employee Number :1
Enter Employee Name:Krish
Enter Department :Accounts
Enter Employee Salary:40000
row inserted successfully...
Do You Want to enter more records?(y/n)y
Enter Employee Number :2
Enter Employee Name:Shyam
Enter Department :Production
Enter Employee Salary:35000
row inserted successfully...
Do You Want to enter more records?(y/n)n
(1, 'Krish', 'Accounts', 40000.0)
(2, 'Shyam', 'Production', 35000.0)
Total number of rows retrieved= 2

(37)
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:
import mysql.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'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO SEARCH :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
print("%10s"%"EMPNO", "%20s"%"NAME","%15s"%"DEPARTMENT",
"%10s"%"SALARY")
for row in result:
print("%10s"%row[0],"%20s"%row[1],"%15s"%row[2],"%10s"%row[3])
ans=input("SEARCH MORE (Y) :")

output:

########################################
EMPLOYEE SEARCHING FORM
########################################
ENTER EMPNO TO SEARCH :1
EMPNO NAME DEPARTMENT SALARY
1 Krish Accounts 40000.0

SEARCH MORE (Y) :n

(38)
19. Write a Program to integrate SQL with Python by importing the MYSQL module to
update the employee record of entered empno.
Program:
import mysql.connector as mycon
con = mycon.connect(host='localhost',user='root',password="1234", database="svvv")
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(empno)

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 you sure to update? (Y) :")

if choice.lower()=='y':

print("== You can update the details ==")

d = input("Enter new Department:")


if d=="":
d=row[2]

(39)
try:

n = input("Enter new Name: ")


s = int(input("Enter new Salary: "))

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

Enter Empno to update:2


EMPNO NAME DEPARTMENT SALARY
2 Shyam Production 35000.0

## Are you sure to update? (Y) :y


== You can update the details ==
Enter new Department:Production
Enter new Name: Shyam
Enter new Salary: 50000
## RECORD UPDATED ##
Do you want to update more? (Y)n

(40)
20.Program to integrate SQL with Python by importing the MYSQL module to delete the
record of entered employee number.
Program:
import mysql.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'
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) :")

Output:
########################################
EMPLOYEE DELETION FORM
########################################

ENTER EMPNO TO DELETE :2


EMPNO NAME DEPARTMENT SALARY
2 Shyam Production 50000.0

## ARE YOUR SURE TO DELETE ? (Y) :y


=== RECORD DELETED SUCCESSFULLY==
DELETE MORE ? (Y) :n

(41)

You might also like