Akshita
Akshita
Write a program to write the function checkprime () ,to check whether the given number is
1. prime or not.
Write the program to find the factorial of a given number using recursive and non-recursive
2. methods.
Write a program to find the n number of terms in the fibonacci series using recursive and
3. non-recursive methods.
WAP to read a set of n numbers and then perform binary search ( recursive and non recursive )
4. to search for a target value t.
WAP to read a set of n numbers and then perform linear search ( recursive and non recursive )
5. to search for a target value t.
WAP to Generate 3 random integers between 100 and 999 which is divisible by 5
6.
WAP to Generate 6 digit random number OTP .
7.
WAP to Pick three lucky tickets winners . The registration numbers of the ticket are 10 digits
8. long.
Write a Program that reads a string and then prints a string that capitalizes every other letter
11. in the string.
Write a Program that reads a string and find the sum of all the digits present in
12. that string.
For ex: If user enters: Python@2021
Then output of the program should be: 5
Write a Program to enter N integer elements in a Tuple and check whether all the elements are
13. in ascending order or not.
Write a program to enter N Tuple pairs ((2,3),(4,5)……) ) and display total number of pairs
14. (a,b) such that both a and b are even.
Write a Program to create a dictionary containing name of the students as key and their marks
15. in 5 subjects as value separately and display information of those students whose name ends
with a.
Write a Program that inputs a line of text and print the biggest word (length wise) from it.
16.
Write a Program to enter N elements of integer type in a list and rearrange the elements as per
17. the following.if input list L1 contains
2 5 7 9 4 8 3 1 10 6
6 2 5 7 9 4 8 3 1 10
Write a Program to create a dictionary for employees containing N elements { name : salary }
19. where N is entered by user and delete the element from the dictionary whose name starts with
'A' and ends with 'a', also count number of employees deleted.
Suppose we have a list L1 where each element represents the visit dates for a particular patient
20. in the last month. We want to calculate the highest numbers of visits made by any patient.
Write a Program to do this.
A Sample list L1 is shown below.
L1=[ [3,9], [13,20], [25], [13], [1,8,15,22,29,30], [10], [12,18,19] ]
For the above given list L1, the program should display the result
as [1,8,15,22,29,30]
Write a Program to enter information N students as a Tuple (rn, name and (marks in 5 subjects
22. as a Tuple)) and display the grade of each student with name.
Percentage : Grade
>90 : A
>80 : B
>70 : C
>60 : D
>50 : E
<=50 : F
Write a program using a user defined function myMean() to calculate the mean of floating
23. values passed as an argument. Use variable length arguments.
Write a program using a user defined function that accepts the first cname and lastname as
24. arguments, concatenate them to get full name and displays the output as: Hello full name
Write a program that simulates a traffic light . The program should consist of the following:
25. 1. A user defined function trafficLight( ) that accepts input from the user, displays an
error message if the user enters anything other than RED, YELLOW, and GREEN.
Function light() is called and the following is displayed depending upon return value
from light().
a) “STOP, your life is precious” if the value returned by light() is 0.
b) “Please WAIT, till the light is Green “ if the value returned by light() is 1
c) “GO! Thank you for being patient” if the value returned by light() is 2.
2. A user defined function light() that accepts a string as input and returns 0 when
the input is RED, 1 when the input is YELLOW and 2 when the input is GREEN. The
input should be passed as an argument.
3. Display “ SPEED THRILLS BUT KILLS”
create a user defined module basic_ math that contains the following user defined functions:
26. a. To add two numbers and return their sum.
b. To subtract two numbers and return their difference.
c. To multiply two numbers and return their product.
d. To divide two numbers and return their quotient and print “Division by Zero” error
if the denominator is zero.
Create a menu driven program using user defined functions to implement a calculator that
27. performs the following:
a) Basic arithmetic operations(+,-,*,/) b) log10(x),sin(x),cos(x)
After creating module, import and execute functions.
To secure your account, whether it be an email, online bank account or any other account, it is
28. important that we use authentication. Use your programming expertise to create a program
using user defined function named login that accepts userid and password as parameters
(login(uid,pwd)) that displays a message “account blocked” in case of three wrong attempts.
The login is successful if the user enters user ID as "ADMIN" and password as "St0rE@1". On
successful login, display a message “login successful”.
ABC School has allotted unique token IDs from (1 to 600) to all the parents for facilitating a
29. lucky draw on the day of their Annual day function. The winner would receive a special prize.
Write a program using Python that helps to automate the task.(Hint: use random module)
Write a program that has a user defined function to accept the coefficients of a quadratic
30. equation in variables and calculates its determinant. For example : if the coefficients are stored
in the variables a,b,c then calculate determinant as b2-4ac. Write the appropriate condition to
check determinants on positive, zero and negative and output appropriate result.
Write a program that creates a GK quiz consisting of any five questions of your choice. The
31. questions should be displayed randomly. Create a user defined function score() to calculate the
score of the quiz and another user defined function remark (scorevalue) that accepts the final
score to display remarks as follows:
Marks Remarks
5 Outstanding
4 Excellent
3 Good
2 Read more to score more
1 Needs to take interest
0 General knowledge will always help you. Take it seriously.
WAP to read a list of n numbers and sort it using bubble sort method.
32.
Write a method in Python to read lines from a text file DIARY.TXT, and display those lines, which
33. are starting with an alphabet ‘s’
Reena has used a text editing software to type some text. After saving the article as
34. WORDS.TXT, she realised that she has wrongly typed alphabet J in place of alphabet I
everywhere in the article.
Write a function definition for JTOI()in python that would display the corrected version of
entire content of the file WORDS.TXT with all the alphabets “J” to be displayed as an alphabet
“I” on screen.
Note : Assuming that WORD.TXT does not contain any J alphabet otherwise.
Example : If Reena has stored the following content in the file WORDS.TXT :
WELL, THJS JS A WORD BY JTSELF. YOU COULD STRETCH THJS TO BE A SENTENCE
The function JTOI( ) should display the following content :
WELL, THIS IS A WORD BY ITSELF. YOU COULD STRETCH THIS TO BE A SENTENCE
Write a method in Python to read lines from a text file NOTES.TXT, and count those lines, which
35. are ending with ‘.’ or ‘,’.
Write a function definition ARTICLES() in python to count all the articles “the”, “a” and “an”
36. present in a text file “BOOK.TXT”.
Note : Ensure that “the”, “a” and “an” are counted as independent words and not as a part of
any other word.
Example : If the following is content in the file BOOK.TXT :
We should choose a low fat diet. The chef is really good in the hotel. An article came in the
newspaper about him.
The function ARTICLE( ) should display the following output : 5
Write a function definition remove () in python to remove all the articles “the”, “a” and “an”
37. and short words like “is”, “on”,”in”,”of” present in a text file “BOOK.TXT”.
Example : If the following is content in the file BOOK.TXT :
We should choose a low fat diet. The chef is really good in the hotel. An article came in the
newspaper about him.
The function remove() should display the following output :
We should choose low fat diet.chef really good hotel.article came newspaper about him.
Create a CSV file “Groceries” to store information of different items existing in a shop. The
38. information is to be stored w.r.t. each item name, price, qty. Write a program to accept the data
from user and store it permanently in CSV Read the file to display the records in the following
format:
Item No:
Item Name :
Quantity:
Price per item:
Amount:
Create a file called contact.csv which contains the details of a person (name , phone and city),
42. Write the python code to perform the following functions :
1. Add a record in the file
2. Display all records
3. Search details by the name
4. Search details by city
5. Update the phno and city of a given name
6. Delete a particular record
7. Exit
43. Write a menu driven program to perform the following operations in a Linear List using Stack.
1.Push 2.Pop 3.Display 4. Count 5. Exit
Write a python program to check whether a string is a palindrome or not using stack.
44.
Write a program to implement all stack operations (push,pop,display ) for
45. the employee details (empno, name).
Write a Program to perform push and pop operations on a stack containing members details as
46. follows : Member number , name and age . Also write code to display and count he members in
the stack.
Create the database product and then create the following table item in it.
47. Column name Data type Size Constrain
Itemno Number 3 Primary key
Iname Varchar 15
Price Number 10,2
Quantity Number 3
In a database product their are two tables , Write the following Queries :
52.
Write the SQL commands for (i) to (v) on the basis of tables following table:
57.
(i) To show Book name, Author name and Price of books of ABC publisher.
(ii) To display the details of the books in descending order of their price.
(iii) To display the Book Id, Book name, Publisher, Price, Qty, Qty_Issued from both the tables
with their matching Book ID.
Write a menu based program to perform the following operation on Customer Details using
58. Interfacing Python with MySQL
1. Add new record
2. Display all the record
3. Search record based on Cust_Id
Write a menu based program to perform the following operation on Customer Details using
59. Interfacing Python with MySQL
1. Update a record based on Cust_id
2. Delete record based on Cust_Id
3. Display all the record
Write a MySQL connectivity program in Python to Create a database school and then create
60. Create a table book with the specifications – Book_id , book_title, Author , Price , Qty , and
perform the following operations:
1. Create a table
2. Add a record
3. Search a record
4. Update a record
5. Delete a record
6. Display all records
7. Exit
1. Write a program to write the function checkprime () ,to check
Code:
n=int(input("Enter the number:"))
def checkprime(n):
p=1
for i in range(2,n):
if n%i==0:
p=0
break
if p==0:
print("Not a prime no.")
else:
print("Prime Number")
checkprime(n)
Output:
2. Write the program to find the factorial of a given number using recursive and
non-recursive methods.
Code:
n=int(input("Enter a number:"))
def factorial(n):
p=1
for i in range(n,0,-1):
p=p*i
print(p)
factorial(n)
Output:
3. Write a program to find the n number of terms in the fibonacci series using
recursive and non-recursive methods.
Code:
n=int(input("Enter no. of terms:"))
a=0
b=1
print(a)
print(b)
c=1
while(c<=n-2):
c=a+b
print(c)
a,b=b,c
c+=1
n=int(input("Enter no. of terms:"))
def fibo(n):
if n<=1:
return n
else:
return(fibo(n-1)+fibo(n-2))
for i in range(n):
print(fibo(i))
fibo(n)
Output:
4. WAP to read a set of n numbers and then perform binary search ( recursive
and non recursive ) to search for a target value t.
Code:
Output:
5. WAP to read a set of n numbers and then perform linear search ( recursive
and non recursive ) to search for a target value t.
Code:
def search(L,T,L1):
if L1[0]==T:
return L.index (L1[0])
else:
L1.pop(0)
return search (L,T,L1)
n=int(input("Enter number of terms :"))
L=[]
for i in range (n):
elm=int(input("Enter the element :"))
L.append(elm)
T=int(input("Enter the target element "))
L1=L[:]
if search (L,T,L1)>=0:
print ("Element found at position", search(L,T,L1)+1)
else:
print ("Element not found")
Output:
6. WAP to Generate 3 random integers between 100 and 999 which is divisible
by 5
Code:
import random
for i in range(3):
print(random.randrange(100,1000,5))
Output:
7. WAP to Generate 6 digit random number OTP .
Code:
import random
l=["0","1","2","3","4","5","6","7","8","9"]
a=random.choice(l)
b=random.choice(l)
c=random.choice(l)
d=random.choice(l)
e=random.choice(l)
f=random.choice(l)
p=[a,b,c,d,e,f]
k=""
for i in p:
k += i
print ("OTP:",k)
Output:
8. WAP to Pick three lucky tickets winners . The registration numbers of the
ticket are 10 digits long.
Code:
import random
l=["0","1","2","3","4","5","6","7","8","9"]
for j in range(3):
a=random.choice(l)
b=random.choice(l)
c=random.choice(l)
d=random.choice(l)
e=random.choice(l)
f=random.choice(l)
g=random.choice(l)
h=random.choice(l)
i=random.choice(l)
j=random.choice(l)
p=[a,b,c,d,e,f,g,h,i,j]
k=""
for i in p:
k += i
print ("Lucky Winner:",k)
Output:
0. Write the code to Pick a random character from a given String.
Code:
import random
n=input("Enter your string:")
a=random.choice(n)
print(a)
Output:
0. Generate a random Password which meets the following conditions :
a. Password length must be 10 characters long.
a. It must contain at least 2 upper case letters, 1 digit, and 1 special symbol.
Code:
import random
l=['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']
m=['0','1','2','3','4','5','6','7','8','9']
o=['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']
p=['!','@','#','$','%','^','&','*','<','>','?']
a=random.sample(o,3)
b=random.sample(l,3)
c=random.sample(m,2)
d=random.sample(p,2)
f=a+b+c+d
k=""
t=random.shuffle(f)
for i in f:
k+=i
print(k)
Output:
0. Write a Program that reads a string and then prints a string that capitalizes
every other letter in the string.
Code:
Output:
0. Write a Program that reads a string and find the sum of all the digits present
in that string.
For ex: If user enters: Python@2021
Code:
s=0
n=input("Enter your string:")
for i in n:
if i.isdigit()==True:
s=s+int(i)
print("Sum is:",s)
Output:
0. Write a Program to enter N integer elements in a Tuple and check whether all
the elements are in ascending order or not.
Code:
n=int(input("Enter the number of elements:"))
t=()
for i in range(n):
e=int(input("Enter an element of a tuple:"))
t=t+(e,)
print(t)
sort=True
for i in range(n-1):
if t[i]>t[i+1]:
sort=False
break
if sort==True:
print("Tuple is in ascending order>")
else:
print("Tuple is not in ascending order.")
Output:
0. Write a program to enter N Tuple pairs ((2,3),(4,5)……) ) and display total
number of pairs (a,b) such that both a and b are even.
Code:
Output:
0. Write a Program to create a dictionary containing name of the students as
key and their marks in 5 subjects as value separately and display information of
those students whose name ends with a.
Code:
k="a"
D={}
for key in d:
if(key[-1]==k):
D[key]=d[key]
Output:
0. Write a Program that inputs a line of text and print the biggest word (length
wise)
from it.
Code:
n=input("Enter a string:")
words=n.split()
longword=""
for w in words:
if len(w)>len(longword):
longword=w
print("Longest word:",longword)
Output:
0. Write a Program to enter N elements of integer type in a list and rearrange
the elements as per the following.if input list L1 contains
2 5 7 9 4 8 3 1 1 6
0
6 2 5 7 9 4 8 3 1 1
0
Code:
n=int(input("Enter the no. of terms:"))
l=[]
for i in range(n):
e=int(input("Enter the number:"))
l.append(e)
print(l)
a=l[-1]
l.insert(0,a)
l.pop(-1)
print(l)
Output:
0. WAP in Python to display the following pattern.
5
45
345
2345
12345
Code:
n=int(input("Enter a number:"))
for i in range(n,0,-1):
for j in range(i,n+1):
print(j,end="")
print()
Output:
0. Write a Program to create a dictionary for employees containing N elements { name :
salary } where N is entered by user and delete the element from the dictionary whose name
starts with 'A' and ends with 'a', also count number of employees deleted.
Code:
n=int(input("Enter the number of elements:"))
d={}
c=0
for i in range(n):
nm=input("Enter the name:")
s=int(input("Enter the salary:"))
d[nm]=[s]
print("Total Employees:",d)
k="A"
p="a"
D={}
for key in d:
if(key[0]==k) and (key[-1]==p):
D[key]=d[key]
c=c+1
print ("Deleted Employee:",str(D))
print("Number of employees deleted:",c)
Output:
0. Suppose we have a list L1 where each element represents the visit dates for
a particular patient in the last month. We want to calculate the highest numbers
of visits made by any patient. Write a Program to do this.
Code:
Output:
0. A dictionary D1 has values in the form of list of integers. Write a Program to
a. create a new dictionary D2 having same keys as D1 but values as the
average of the list elements.
Code:
n=int(input("Enter number of dictionary pairs:"))
d={}
for i in range(n):
a=input("Enter the key:")
b=int(input("Enter the no. of elements of values:"))
l=[]
for j in range(b):
c=int(input("Enter the value:"))
l.append(c)
d[a]=l
print(d)
def avgofl(y):
a=int()
l=y
for j in l:
a=a+j
avg=a/len(l)
return avg
D={}
for k,y in d.items():
x=avgofl(y)
D[k]=x
print(D)
Output:
0. Write a Program to enter information N students as a Tuple (rn, name and
(marks in 5 subjects as a Tuple)) and display the grade of each student with name.
Percentage : Grade
>90 : A
>80 : B
>70 : C
>60 : D
>50 : E
<=50 : F
Code:
n=int(input("Enter the no. of students:"))
t=()
r=()
l=[]
for i in range(n):
t=()
rn=int(input("Enter the roll no.:"))
nm=input("Enter the name:")
e=int(input("Enter the marks in english:"))
m=int(input("Enter the marks in maths:"))
p=int(input("Enter the marks in physics:"))
c=int(input("Enter the marks in chemistry:"))
cs=int(input("Enter the marks in computer science:"))
r=(e,m,p,c,cs,)
f=((e+m+p+c+cs)/500)*100
t=(rn,nm,r,f,)
l.append(t)
print(l)
if f>=90:
print("Name:",nm,"Grade:A")
elif f>=80:
print("Name:",nm,"Grade:B")
elif f>=70:
print("Name:",nm,"Grade:C")
elif f>=60:
print("Name:",nm,"Grade:D")
elif f>=50:
print("Name:",nm,"Grade:E")
elif f<=50:
print("Name:",nm,"Grade:F")
Output:
0. Write a program using a user defined function myMean() to calculate the
mean of floating values passed as an argument. Use variable length arguments.
Code:
def myMean():
L=[]
n=int(input("Enter how many numbers you want to enter :"))
for i in range (n):
ele=float(input("Enter float values :"))
L.append(ele)
print ("Mean=",sum(L)/len(L))
myMean()
Output:
0. Write a program using a user defined function that accepts the first cname
and last name as arguments, concatenate them to get full name and displays the
output as: Hello full name
Code:
def Name():
str1=input("Enter first name :")
str2=input("Enter last name :")
print ("Hello", str1 + str2)
Name()
Output:
0. Write a program that simulates a traffic light . The program should consist of
the following:
1. A user defined function trafficLight( ) that accepts input from the user, displays an error
message if the user enters anything other than RED, YELLOW, and GREEN.
Function light() is called and the following is displayed depending upon return value from
light().
a) “STOP, your life is precious” if the value returned by light() is 0.
b) “Please WAIT, till the light is Green “ if the value returned by light() is 1
c) “GO! Thank you for being patient” if the value returned by light() is 2.
2. A user defined function light() that accepts a string as input and returns 0 when the input
is RED, 1 when the input is YELLOW and 2 when the input is GREEN. The input should be
passed as an argument.
3. Display “ SPEED THRILLS BUT KILLS”
Code:
def trafficlight() :
signal=input("Enter the name of color RED YELLOW GREEN : ")
if signal not in ('RED' ,'YELLOW', 'GREEN'):
print("Enter valid color in CAPITAL only")
else:
value=light(signal)
if value ==0:
print('STOP your life is precious')
elif value == 1:
print('READY to go')
else:
print('Thank you for being patient')
def light(color):
if color =='RED':
return 0
elif color== 'YELLOW':
return 1
else:
return 2
trafficlight()
print('BYE BYE')
Output:
0. create a user defined module basic_ math that contains the following user
defined functions:
a. To add two numbers and return their sum.
a. To subtract two numbers and return their difference.
b. To multiply two numbers and return their product.
c. To divide two numbers and return their quotient and print “Division by Zero”
error if the denominator is zero.
Code:
def add():
print("The sum is:",n+m)
def subtract():
print("The difference is:",n-m)
def product():
print("The product is:",n*m)
def divide():
print("The quotient is:",n/m)
Output:
0. Create a menu driven program using user defined functions to implement a
calculator that performs the following:
Code:
x = int(input ("Enter the first number : " ) )
y= int(input ("Enter the second number : " ) )
if n == 1 :
print("The result of addition : " , (x+y))
elif n==2 :
print("The result of substraction : " , (x-y))
elif n==3 :
print("The result of multiplication : " , (x*y))
elif n==4 :
print("The result of division : " , (x/y))
else:
print("Invalid Choice")
import math
Output:
0. To secure your account, whether it be an email, online bank account or any
other account, it is important that we use authentication. Use your programming
expertise to create a program using user defined function named login that accepts
userid and password as parameters (login(uid,pwd)) that displays a message
“account blocked” in case of three wrong attempts. The login is successful if the user
enters user ID as "ADMIN" and password as "St0rE@1". On successful login,
display a message “login successful”.
Code:
counter=0
def user():
user_id=input("Enter user id :")
pswd=input("Enter password :")
login (user_id,pswd)
def login(uid,pwd):
global counter
if(uid=="Admin" and pwd=="Str0rE@1"):
print("Login")
return
else:
counter+=1
print("The user id and password is incorrect !!")
if counter >2:
print("ACCOUNT BLOCKED!!")
return
else:
print ("Try again !!")
user()
user()
Output:
0. ABC School has allotted unique token IDs from (1 to 600) to all the parents for
facilitating a lucky draw on the day of their Annual day function. The winner would
receive a special prize. Write a program using Python that helps to automate the
task.(Hint: use random module from random
Code:
import randint
def generateRandom():
print("The winner of the lucky draw is the parent with token id: ",randint(1, 600))
print("")
generateRandom()
Output:
0. Write a program that has a user defined function to accept the coefficients of a
quadratic equation in variables and calculates its determinant. For example : if the
coefficients are stored in the variables a,b,c then calculate determinant as b2-4ac.
Write the appropriate condition to check determinants on positive, zero and negative
and output appropriate result.
Code:
import math
def findRoots(a, b, c):
if a == 0:
print("Invalid")
return -1
d=b*b-4*a*c
sqrt_val = math.sqrt(abs(d))
if d > 0:
print("Roots are real and different ")
print((-b + sqrt_val)/(2 * a))
print((-b - sqrt_val)/(2 * a))
elif d == 0:
print("Roots are real and same")
print(-b / (2*a))
else:
print("Roots are complex")
a=2
b=6
c=3
findRoots(a, b, c)
Output:
0. Write a program that creates a GK quiz consisting of any five questions of
your choice. The questions should be displayed randomly. Create a user defined
function score() to calculate the score of the quiz and another user defined function
remark (scorevalue) that accepts the final score to display remarks as follows:
Marks Remarks
5 Outstanding
4 Excellent
3 Good
Code:
import random
quiz = ["What is the capital of Uttar Pradesh?","How many states are in North-East India?"]
ans = ["LUCKNOW","EIGHT","MUMBAI","VANDE MATARAM","KERALA"]
userInp = []
sequence = []
remarks =["General knowledge will always help you. Take it seriously", "Needs to take
interest>"]
def score():
s=0
for i in range(0,5):
if(userInp[i] == ans[sequence[i]]):
s += 1
return s
def remark(score):
print(remarks[score])
def disp(r):
print(quiz[r])
inp = input("Answer:")
userInp.append(inp.upper())
sequence.append(r)
i = 0;
while i < 5:
r = random.randint(0, 4)
if(r not in sequence):
i += 1
disp(r)
s = score()
print("Your score :", s, "out of 5")
remark(s)
Output:
0. WAP to read a list of n numbers and sort it using bubble sort method.
Code:
def bubbleSort(L):
n = len(L)
swapped = False
for i in range(n-1):
for j in range(0, n-i-1):
if L[j] > L[j + 1]:
swapped = True
L[j], L[j + 1] = L[j + 1], L[j]
if not swapped:
return
L=[]
n=int(input("Enter how many elements you want to add :"))
for i in range (n):
ele=int(input("Enter elements :"))
L.append(ele)
bubbleSort(L)
print("Sorted list is:")
for i in range(len(L)):
print("% d" % L[i], end=" ")
Output:
33. Write a method in Python to read lines from a text file DIARY.TXT, and display
those lines, which are starting with an alphabet ‘s’.
Code:
f=open("Diary.txt",'r')
a=f.readlines()
for i in range(len(a)):
if a[i][0]=="s":
print (a[i])
f.close()
Output:
34. Reena has used a text editing software to type some text. After saving the article as WORDS.TXT, she
realised that she has wrongly typed alphabet J in place of alphabet I everywhere in the article.
Write a function definition for JTOI()in python that would display the corrected version of entire content of the file
WORDS.TXT with all the alphabets “J” to be displayed as an alphabet “I” on screen.
Note : Assuming that WORD.TXT does not contain any J alphabet otherwise.
Example : If Reena has stored the following content in the file WORDS.TXT :
Code:
def JTOI():
f=open("Word.txt",'r+')
S=f.read()
print(S)
Si=S.replace('J','I')
f.close()
f=open("Word.txt",'w')
f.write(Si)
f.close()
f=open("Word.txt",'r')
print(f.read())
JTOI()
Output:
35. Write a method in Python to read lines from a text file NOTES.TXT, and
count
Code:
f=open("Notes.txt",'r')
c=0
a=f.readlines()
print (a)
for i in range (len(a)):
if "." in a[i] or "," in a[i]:
c+=1
f.close()
print("Number of lines ending with '.' or ',':",c)
Output:
36. Write a function definition ARTICLES() in python to count all the articles “the”, “a” and “an” present in a
text file “BOOK.TXT”.
Note : Ensure that “the”, “a” and “an” are counted as independent words and not as a part of any other
word.
We should choose a low fat diet. The chef is really good in the hotel. An article came in the newspaper
about him.
Code:
f=open("Books.txt",'r')
S=f.read()
print (S)
w=S.split()
new=''
St=["a","an","the","to","on","from","in","is","we"]
for i in w:
if i not in St:
new=new+i
f.close()
f=open("Books.txt",'w')
f.write(new)
f.close()
f=open("Books.txt",'r')
print ("Updates file :-", f.read())
Output:
37. Write a function definition remove () in python to remove all the articles “the”,
“a” and “an” and short words like “is”, “on”,”in”,”of” present in a text file “BOOK.TXT”.
We should choose a low fat diet. The chef is really good in the hotel. An article came
in the newspaper about him.
We should choose low fat diet.chef really good hotel.article came newspaper about
him.
Code:
def remove():
f=open('Books.txt','r')
c=f.read()
a=c.split()
r=['a','an','the','is','on','in','of','The','An']
for i in a:
if i.lower() in r:
continue
print(i,end=' ')
f.close()
remove()
Output:
38. Create a CSV file “Groceries” to store information of different items existing in
a shop. The information is to be stored w.r.t. each item name, price, qty. Write a
program to accept the data from user and store it permanently in CSV Read the file
to display the records in the following format:
Item No:
Item Name :
Quantity:
Price per item:
Amount:
Code:
import csv
def addrec():
f=open("Groceries.csv",'a+',newline='')
fw=csv.writer(f)
while True:
itna=input("Enter name of the item :")
Quan=int(input("Enter quantity of item :"))
Price=input("Enter price per unit :")
Amnt=int(input("Enter amount :"))
fw.writerow([itna,Quan,Price,Amnt])
ch=input("Do you want to continue (y/n)")
if ch in 'nN':
break
f.close()
addrec()
f=open("Groceries.csv",'r')
fr=csv.reader(f)
for i in fr:
print(i)
f.close()
Output:
39. Consider a binary file Stock.dat that has the following data:
OrderId,
MedicineName,
Quantity
Price of all the Medicines of Wellness Medicos.
Write the following functions:
(i) AddOrder() that can input all the medicine orders.
(ii) DisplayPrice() to display the price of all the medicines that have price >
500.
(iii) Modifyorder() to modify the order details
(iv) Deleteorder() to delete order details
Code:
import pickle
def addorder():
N=int(input("Enter the number of records:"))
f=open("Student.dat",'wb')
for i in range(N):
r=int(input("Enter order id:"))
n=input("Enter medicine name:")
m=int(input("Enter quantity:"))
p=input("Enter price:")
D={}
D["order id"]=r
D["medicine name"]=n
D["quantity"]=m
D["price"]=p
pickle.dump(D,f)
f.close()
def displayprice():
f=open("Student.dat",'rb')
try:
while True:
D=pickle.load(f)
print(D)
except EOFError:
pass
f.close()
def modifyorder():
r=int(input("Enter order id:"))
m=int(input("Enter updated quantity:"))
f=open("Student.dat",'rb')
L=[]
try:
while True:
D=pickle.load(f)
L.append(D)
except EOFError :
pass
f.close()
f=open("Student.dat",'wb')
for i in L:
if i["order id"]==r:
i["quantity"]=m
pickle.dump(i,f)
f.close()
def deleteorder():
r=int(input("Enter order-id :"))
f=open("Student.dat",'rb')
L=[]
try:
while True:
D=pickle.load(f)
L.append(D)
except EOFError:
pass
f.close()
f=open("Student.dat",'wb')
for i in L:
if i["order id"]==r:
continue
pickle.dump(i,f)
f.close()
while True:
print("1. Adding a record")
print("2. Display price")
print("3. Modify a record")
print("4. Delete a record")
print("5. Exit")
ch=input("Enter your choice:")
if ch=="1":
addorder()
elif ch=="2":
displayprice()
elif ch=="3":
modifyorder()
elif ch=="4":
deleteorder()
else:
break
Output:
Code:
import pickle
def addorder():
N=int(input("Enter the number of records:"))
f=open("PRODUCT.dat",'wb')
for i in range(N):
r=input("Enter product code:")
n=input("Enter product description:")
m=int(input("Enter stock:"))
D={}
D["product code"]=r
D["product description"]=n
D["stock"]=m
pickle.dump(D,f)
f.close()
addorder()
def modifyorder():
r=input("Enter product code:")
m=input("Enter updated code:")
f=open("PRODUCT.dat",'rb')
L=[]
try:
while True:
D=pickle.load(f)
L.append(D)
except EOFError :
pass
f.close()
f=open("PRODUCT.dat",'wb')
for i in L:
if i["product code"]==r:
i["updates code"]=m
pickle.dump(i,f)
f.close()
modifyorder()
def display():
f=open("PRODUCT.dat",'rb')
try:
while True:
D=pickle.load(f)
print(D)
except EOFError:
pass
f.close()
display()
Output:
41. Given a binary file “STUDENT.DAT”, containing records of the following type:
[S_Admno, S_Name, Percentage]
Where these three values are:
S_Admno – Admission Number of student (string)
S_Name – Name of student (string)
Percentage – Marks percentage of student (float)
Write the functions in Python :
that would read contents of the file “STUDENT.DAT” and display the details of those
students whose percentage is above 75.
Add the student record
Delete the student record
Modify the student record
Code:
import pickle
def addrec():
S_Admno=input("Enter your admission number:")
S_Name=input("Enter Name:")
Percentage=int(input("Enter percentage:"))
d={}
d["Admission No."]=S_Admno
d["Name"]=S_Name
d["Marks"]=Percentage
f=open("Student.dat",'ab')
pickle.dump(d,f)
f.close()
def display():
f=open("Student.dat",'rb')
try:
while True:
D=pickle.load(f)
print(D)
except EOFError:
pass
f.close()
def modify():
r=int(input("Enter student percentage:"))
m=int(input("Enter updated percentage:"))
f=open("Student.dat",'rb')
L=[]
try:
while True:
D=pickle.load(f)
L.append(D)
except EOFError :
pass
f.close()
f=open("Student.dat",'wb')
for i in L:
if i["percentage"]==r:
i["updated percentage"]=m
pickle.dump(i,f)
f.close()
def delete():
r=input("Enter student Admission No.:")
f=open("Student.dat",'rb')
L=[]
try:
while True:
D=pickle.load(f)
L.append(D)
except EOFError:
pass
f.close()
f=open("Student.dat",'wb')
for i in L:
if i["Admission No."]==r:
continue
pickle.dump(i,f)
f.close()
while True:
print("1. Adding a record")
print("2. Display price")
print("3. Modify a record")
print("4. Delete a record")
print("5. Exit")
ch=input("Enter your choice:")
if ch=="1":
addrec()
elif ch=="2":
display()
elif ch=="3":
modify()
elif ch=="4":
delete()
else:
break
Output:
42 Create a file called contact.csv which contains the details of a person (name ,
phone and city), Write the python code to perform the following functions :
7. Exit
Code:
import csv
def add():
f=open("contact.csv","a",newline="")
fw=csv.writer(f)
fr=csv.reader(f)
if fr.line_num==0:
H=["NAME","CONTACT","CITY"]
fw.writerow(H)
while True:
n=input("ENTER NAME: ")
contact=input("ENTER CONTACT: ")
city=input("ENTER CITY: ")
fw.writerow([n,contact,city])
ch=input("DO YOU WANT TO ENTER MORE?(Y/N)")
if ch in "Nn":
break
f.close()
def searchN():
c=0
name=input("ENTER NAME TO SEARCH")
f=open("contact.csv","r")
fr=csv.reader(f)
for i in fr:
if i[0]==name:
print("CONTACT NO.-",i[1],"city-",i[2])
c=1
if c==0:
print("NAME IS NOT IN THE CONTACT LIST!!")
f.close()
def searchC():
c=0
me=input("ENTER CONTACT NO. TO SEARCH")
f=open("contact.csv","r")
fr=csv.reader(f)
for i in fr:
if i[1]==me:
print("NAME-",i[0],"city-",i[2])
c=1
if c==0:
print("CONTACT NO. IS NOT IN THE CONTACT LIST!!")
f.close()
def update():
c=0
L=[]
name=input("ENTER NAME TO update")
ph=int(input("ENTER UPDATED NO.-"))
city=input("ENTER UPDATED CITY-")
f=open("contact.csv","r")
fr=csv.reader(f)
for i in fr:
if i[0]==name:
i[1]=ph
i[2]=city
c=1
L.append(i)
if c==0:
print("NAME IS NOT IN THE CONTACT LIST!!")
f.close()
f=open("contact.csv","w",newline="")
fw=csv.writer(f)
for i in L:
fw.writerow(i)
print("updated succesfully")
f.close()
def delete():
c=0
L=[]
name=input("ENTER NAME TO update")
f=open("contact.csv","r")
fr=csv.reader(f)
for i in fr:
if i[0]==name:
c=1
L.append(i)
if c==0:
print("CONTACT NO. IS NOT IN THE CONTACT LIST!!")
f.close()
f=open("contact.csv","w",newline="")
fw=csv.writer(f)
for i in L:
if i[0]==name:
continue
fw.writerow(i)
print("deleted succesfully")
f.close()
while True:
print("1. ADD A RECORD")
print("2. SEARCH A RECORD BY NAME")
print("3. SEARCH A RECORD BY CONTACT NO. ")
print("4. UPDATE A RECORD")
print("5. DELETE A RECORD")
print("6. EXIT")
ch=input("ENTER YOUR CHOICE")
if ch=="1":
add()
elif ch=="2":
searchN()
elif ch=="3":
searchC()
elif ch=="4":
update()
elif ch=="5":
delete()
elif ch=="6":
break
else:
print("invalid!!")
print()
Output:
.43. Write a menu driven program to perform the following operations in a Linear List
using Stack.
1.Push
2.Pop
3.Display
4. Count
5. Exit
Code:
S=[]
def push():
def pop():
if S==[]:
print ("Stack is empty :")
else:
p=S.pop()
print ("Popped element is",p)
def display():
for i in range (len(S)-1,-1,-1):
print (S[i])
while True:
print ("1.Push an element")
print ("2,.Pop an element")
print ("3.Display stack")
print ("4.Exit")
ch=int(input("Enter your choice:"))
if ch==1:
push()
elif ch==2:
pop()
elif ch==3:
display()
elif ch==4:
break
else:
print("Invalid choice")
Output:
44. Write a python program to check whether a string is a palindrome or not
using stack.
Code:
s=input('Enter String:')
s1=list(s)
stack=[]
def push(stack,e):
stack.append(e)
for i in range(len(s1)-1,-1,-1):
stack.append(s1[i])
if s1==stack:
print(s,'is palindrome')
else:
print(s,'is not palindrome')
Output:
stack=[]
def push():
while True:
e=int(input("Enter Employee Number:"))
n=input("Enter your name:")
stack.append([e,n])
ans=input("Do you want to enter more(y/n):")
if ans=="n" or ans=="N":
break
def pop():
if stack==[]:
print("Stack is empty")
else:
p=stack.pop()
print("Popped element:",p[0],p[1])
def display():
for i in range(len(stack)-1,-1,-1):
print(stack[i])
while True:
print("1:Push an element")
print("2:Pop an element")
print("3:Display all elements")
print("4:Exit")
ch=int(input("Enter your choice"))
if ch==1:
push()
elif ch==2:
pop()
elif ch==3:
display()
elif ch==4:
break
else:
print("invalid choice")
print(stack)
Output:
46. Write a Program to perform push and pop operations on a stack containing
members details as follows : Member number , name and age . Also write
code to display and count he members in the stack.
Code:
stack=[]
def push():
while True:
e=int(input("Enter Member Number:"))
n=input("Enter your name:")
a=int(input("Enter your age:"))
stack.append([e,n,a])
ans=input("Do you want to enter more(y/n):")
if ans=="n" or ans=="N":
break
def pop():
if stack==[]:
print("Stack is empty")
else:
p=stack.pop()
print("Popped element:",p[0],p[1],p[2])
def display():
for i in range(len(stack)-1,-1,-1):
print(stack[i])
while True:
print("1:Push an element")
print("2:Pop an element")
print("3:Display all elements")
print("4:Exit")
ch=int(input("Enter your choice"))
if ch==1:
push()
elif ch==2:
pop()
elif ch==3:
display()
elif ch==4:
break
else:
print("invalid choice")
print(stack)
Output:
47. Create the database product and then create the following table item in it.
Column name Data type Size Constrain
Itemno Number 3 Primary key
Iname Varchar 15
Price Number 10,2
Quantity Number 3
Code:
mysql> create database product;
Output:
48. Insert the following information in the above table :
Code:
Output:
49. Write the following queries based on the above item table :
1. Display all items information.
2. Display item name and price value.
3. Display soap information.
4. Display the item information whose name starts with letter 's'.
5. Display a report with item number, item name and total price. (total price =
price * quantity).
6. Display item table information in ascending order based upon item name.
7. Display item name and price in descending order based upon price.
8. Display item name, whose price is in between 50 to 100.
9. To decrease price value by 5%.
Code:
mysql> Select * from items;
Output:
Code:
mysql> Select Iname, Price from items;
Output:
Code:
mysql> Select * from items where Iname="Soap";
Output:
Code:
mysql> Select * from items where Iname like "S%";
Output:
Code:
mysql> Select Itemno, Iname, Price*Quantity as TotalPrice from items;
Output:
Code:
mysql> Select * from items order by Iname;
Output:
Code:
mysql> Select Iname, Price from items order by price desc;
Output:
Code:
mysql> Select Iname from items where price between 50 and 100;
Output:
Code:
mysql> update items set price=price-price*0.05;
Output:
50. Write the following queries based on the above item table :
Code:
mysql> Alter table items
-> add Totalprice float(10,2);
Output:
Code:
mysql> Alter table items
-> Modify column Iname varchar(25);
Output:
Code:
mysql> Update items set Totalprice= Price* Quantity;
Output:
4. Display the item with maximum Price
Code:
mysql> Select max(price) from items;
Output:
Code:
mysql> Delete from items where Iname="Powder";
Output:
Code:
mysql> Alter table items drop column Totalprice;
Output:
7. Remove whole item table structure.
Code:
mysql> Delete from items;
Output:
Code:
mysql> Drop database Product;
Output:
51. Write outputs based upon item table
Code:
select sum(price) from item;
Output:
Code:
select avg(price) from item;
Output:
Code:
select min(price) from item;
Output:
Code:
select max(price) from item;
Output:
Code:
select count(price) from item;
Output:
Code:
select distinct price from item;
Output:
Code:
select count(distinct price) from item
Output:
Code:
select iname, price*quantity from item
Output:
52. In a database product their are two tables , Write the following Queries :
Code:
mysql> Select item.Iname,Price, Bname from item, brand where item.icode=brand.icode and
item.price between 25000 and 30000;
Output:
b) To display ICode, Price and BName of the item, which has IName as
"Television".
Code:
mysql> Select item.Icode,Price,Bname from Item,Brand where item.icode=brand.icode and
item.iname="Television";
Output:
Code:
mysql> Update item set price=price+price*0.1;
Output:
Code:
mysql> Select item.Iname,Bname from item, brand where item.icode=brand.icode;
Output:
53. Create the table Students with the following specifications :
Column name Data type Size Constraints
Adno Integer 3 Primary key
Name Varchar 20
Average Integer 3
Gender Char 1
Scode Integer 4
Code:
mysql> Create table Students
-> (Adno Int(3) Primary Key, Name Varchar(20), Average Int(3), Gender Char(1), Scode
Int(4));
Output:
54. Insert the following information in the above student table:
Code:
mysql> Insert into Students
-> Values(501,"R.Jain",98,"M",111);
mysql> Insert into Students
-> Values(545,"Kavita",73,"F",333);
mysql> Insert into Students
-> Values(705,"K.Rashika",85,"F",111);
mysql> Insert into Students
-> Values(754,"Rahul Goel",60,"M",444);
mysql> Insert into Students
-> Values(892,"Sahil Jain",78,"M",333);
mysql> Insert into Students
-> Values(935,"Rohan Saini",85,"M",222);
mysql> Insert into Students
-> Values(955,"Anjali",64,"F",444);
mysql> Insert into Students
-> Values(983,"Sneha Aggarwal",80,"F",222);
mysql> Select * from students;
Output:
Code:
mysql> select * from students;
Output:
Code:
mysql> Select * from students where Name="Rohan Saini";
Output:
(iii) Display number of students in the table.
Code:
mysql> Select count(Name) from students;
Output:
Code:
mysql> Select Gender, count(Gender) from students group by Gender;
Output:
Code:
mysql> Select * from students order by name;
Output:
(vi) Display students' information in descending order using average marks.
Code:
mysql> Select * from students order by average desc;
Output:
Code:
mysql> Select * from students where Name like"K%";
Output:
Code:
mysql> Select * from students where Name like"%I";
Output:
(ix) Display a report with adno,name,average*5 as total marks from student table.
Code:
mysql> Select Adno, Name, Average*5 as TotalMarks from students;
Output:
(x) Display students' information, whose average marks are in between 80 to 90.
Code:
mysql> Select * from students where Average between 80 and 90;
Output:
56. Write queries based upon above student table.
(i) Display students' info., who are getting average marks of more than 80 and
scode 333.
Code:
mysql> Select * from students where Average>80 and Scode=333;
Output:
(ii) Display students' name and average marks, whose scode is 222 and 333.
Code:
mysql> Select Name, Average from students where Scode=222 or Scode=333;
Output:
(iii) Display sum of average marks.
Code:
mysql> Select sum(Average) from students;
Output:
Code:
mysql> Select max(Average) from students;
Output:
Code:
mysql> Select min(Average) from students;
Output:
(vi) Display average marks for each gender.
Code:
mysql> Select Gender, avg(Average) from students group by Gender;
Output:
(vii) Display maximum, minimum and sum of average marks in each scode.
Code:
mysql> Select Scode, max(Average), min(Average), sum(Average) from students group by
Scode;
Output:
Code:
mysql> Select Scode, count(Name) from students group by Scode;
Output:
57.Write the SQL commands for (i) to (v) on the basis of following tables:
(i) To show Book name, Author name and Price of books of ABC publisher.
Code:
mysql> Select BookName, AuthorName, Price from Books where Publisher="ABC";
Output:
(ii) To display the details of the books in descending order of their price.
Code:
mysql> Select * from Books order by price desc;
Output:
(iii) To display the Book Id, Book name, Publisher, Price, Qty, Qty_Issued from
both the tables with their matching Book ID.
Code:
mysql> Select Books.Book_ID, BookName, Publisher, Price, Qty, Qty_Issued from
Books,Issues where Books.Book_ID = Issues.Book_ID;
Output:
Code:
mysql> Select Publisher, min(Price) from Books group by Publisher;
Output:
Code:
mysql> Select Books.Price, Qty_Issued from Books, Issues where Books.Book_ID=
Issues.Book_ID and Qty_Issued=5;
Output:
58. Write a menu based program to perform the following operation on Customer
Details using Interfacing Python with MySQL
1. Add new record
2. Display all the record
3. Search record based on Cust_Id
Code:
import mysql.connector
mydb=mysql.connector.connect(host="localhost", user="root", password="*******",
database="details")
mycursor=mydb.cursor()
mycursor.execute("Create table Customers(Cust_id int, Cust_name varchar(20), Cust_age int,
DOB date, Outstanding_Amount float);")
def Addrec():
mydb=mysql.connector.connect(host="localhost", user="root", password="*******",
database="details")
mycursor=mydb.cursor()
n=int(input("Enter the number of Records:"))
for i in range(n):
a=int(input("Enter Customer ID:"))
b=input("Enter Customer's Name:")
c=int(input("Enter Customer's Age:"))
d=input("Enter Customer's DOB:")
e=float(input("Enter Customer's oustanding Amount:"))
mycursor.execute("insert into customers values(%s,%s,%s,%s,%s)",(a,b,c,d,e))
mydb.commit()
mydb.close()
def Displayrec():
mydb=mysql.connector.connect(host="localhost", user="root", password="*******",
database="details")
mycursor=mydb.cursor()
mycursor.execute("Select * from Customers")
rows=mycursor.fetchall()
for i in rows:
print(i)
mydb.close()
def Searchrec():
mydb=mysql.connector.connect(host="localhost", user="root", password="*******",
database="details")
mycursor=mydb.cursor()
n=int(input("Enter the Customer's ID to search:"))
mycursor.execute("Select * from Customers where Cust_ID=%s",(n,))
rows=mycursor.fetchall()
for i in rows:
print(i)
mydb.commit
mydb.close()
while True:
print("1. Add a new Record")
print("2. Display all Records")
print("3. Search a Record based on Cust_Id")
print("4. Exit")
ch=int(input("Enter your choice:"))
if ch==1:
Addrec()
elif ch==2:
Displayrec()
elif ch==3:
Searchrec()
elif ch==4:
break
else:
print("Invalid Choice")
Output:
Code:
import mysql.connector
mydb=mysql.connector.connect(host="localhost", user="root", password="*******",
database="me")
mycursor=mydb.cursor()
mycursor.execute("Create table Customer(Cust_id int, Cust_name varchar(20), Cust_age int,
DOB date, Outstanding_Amount float);")
def Updaterec():
mydb=mysql.connector.connect(host="localhost", user="root", password="*******",
database="me")
mycursor=mydb.cursor()
a=int(input("Enter Customer ID to be updated:"))
b=input("Enter Customer's Name:")
c=int(input("Enter Customer's Age:"))
mycursor.execute("update customer set Cust_name=cust_name+%s,
cust_age=cust_age+%s where cust_Id=%s",(b,c,))
mycurdoe.execute("Select * from customer")
rows=cur.fetchall()
for i in rows:
print(i)
mydb.commit()
mydb.close()
def Deleterec():
mydb=mysql.connector.connect(host="localhost", user="root", password="*******",
database="me")
mycursor=mydb.cursor()
n=int(input("Enter the Customer's ID to delete:"))
mycursor.execute("delete from customer where cust_id=%s",(n,))
mycursor.execute("Select * from customer")
rows=mycursor.fetchall()
for i in rows:
print(i)
mydb.commit
mydb.close()
def Displayrec():
mydb=mysql.connector.connect(host="localhost", user="root", password="*******",
database="me")
mycursor=mydb.cursor()
mycursor.execute("Select * from Customer")
rows=mycursor.fetchall()
for i in rows:
print(i)
mydb.close()
def Addrec():
mydb=mysql.connector.connect(host="localhost", user="root", password="*******",
database="me")
mycursor=mydb.cursor()
n=int(input("Enter the number of Records:"))
for i in range(n):
a=int(input("Enter Customer ID:"))
b=input("Enter Customer's Name:")
c=int(input("Enter Customer's Age:"))
d=input("Enter Customer's DOB:")
e=float(input("Enter Customer's oustanding Amount:"))
mycursor.execute("insert into customer values(%s,%s,%s,%s,%s)",(a,b,c,d,e))
mydb.commit()
mydb.close()
while True:
print("1. Update a Record")
print("2. Delete a Record")
print("3. Display all Records")
print("4. Add a Record")
print("5. Exit")
ch=int(input("Enter your choice:"))
if ch==1:
Updaterec()
elif ch==2:
Deleterec()
elif ch==3:
Displayrec()
elif ch==4:
Addrec()
elif ch==5:
break
else:
print("Invalid Choice")
Output:
60 Write a MySQL connectivity program in Python to Create a database
school and then create Create a table book with the specifications –
Book_id , book_title, Author , Price , Qty , and perform the following
operations:
1. Create a table
2. Add a record
3. Search a record
4. Update a record
5. Delete a record
6. Display all records
7. Exit
Code:
import mysql.connector=
mydb=mysql.connector.connect(host="localhost", user="root", password="*******",
database="school")
mycursor=mydb.cursor()
def CreateTable():
mydb=mysql.connector.connect(host="localhost", user="root", password="*******",
database="school")
mycursor=mydb.cursor()
mycursor.execute("Create table book(Book_id int, Book_title varchar(20), Author
varchar(20), Price int, Qty int);")
mydb.commit
mydb.close()
def Addrec():
mydb=mysql.connector.connect(host="localhost", user="root", password="*******",
database="school")
mycursor=mydb.cursor()
n=int(input("Enter the number of Records:"))
for i in range(n):
a=int(input("Enter Book ID:"))
b=input("Enter Book Title:")
c=input("Enter Author's Name:")
d=int(input("Enter Price:"))
e=int(input("Enter Quantity:"))
mycursor.execute("insert into book values(%s,%s,%s,%s,%s)",(a,b,c,d,e))
mydb.commit()
mydb.close()
def Searchrec():
mydb=mysql.connector.connect(host="localhost", user="root", password="*******",
database="school")
mycursor=mydb.cursor()
n=int(input("Enter the Book ID to search:"))
mycursor.execute("Select * from book where Book_ID=%s",(n,))
rows=mycursor.fetchall()
for i in rows:
print(i)
mydb.commit
mydb.close()
def Updaterec():
mydb=mysql.connector.connect(host="localhost", user="root", password="*******",
database="school")
mycursor=mydb.cursor()
a=int(input("Enter Book ID to be updated:"))
b=input("Enter Book Title:")
c=input("Enter Author's Name:")
mycursor.execute("update book set Book_title=Book_title+%s, Author=Author+%s where
Book_Id=%s",(b,c,))
mycurdoe.execute("Select * from book")
rows=cur.fetchall()
for i in rows:
print(i)
mydb.commit()
mydb.close()
def Deleterec():
mydb=mysql.connector.connect(host="localhost", user="root", password="*******",
database="school")
mycursor=mydb.cursor()
n=int(input("Enter the Book ID to delete:"))
mycursor.execute("delete from book where Book_id=%s",(n,))
mycursor.execute("Select * from book")
rows=mycursor.fetchall()
for i in rows:
print(i)
mydb.commit
mydb.close()
def Displayrec():
mydb=mysql.connector.connect(host="localhost", user="root", password="*******",
database="school")
mycursor=mydb.cursor()
mycursor.execute("Select * from book")
rows=mycursor.fetchall()
for i in rows:
print(i)
mydb.close()
while True:
print("1. Create a Table")
print("2. Add a Record")
print("3. Search a Record")
print("4. Update a Record")
print("5. Delete a Record")
print("6. Display all Records")
print("7. Exit")
ch=int(input("Enter your choice:"))
if ch==1:
CreateTable()
elif ch==2:
Addrec()
elif ch==3:
Searchrec()
elif ch==4:
Updaterec()
elif ch==5:
Deleterec()
elif ch==6:
Displayrec()
elif ch==7:
break
else:
print("Invalid Choice")
Output: