You are on page 1of 36

INDEX

S.No. Details of program Page No.


1 Write a menu driven program for the given options using separate
functions for each menu option:-
1. To find factorial of a number. 1-2
2. To find roots of a quadratic equation
3. To reverse a given number
4. Exit
2 Write a menu driven program for a given string using separate functions
for each menu option:-
1. To count number of alphabets, digits and special characters. 3-4
2. To count number of words
3. To check whether the string is a palindrome or not
4. Exit
3 Create a dictionary whose keys are month names and whose values are the
number of days in the corresponding months. Then run the given menu on
the dictionary.
1. Ask the user to enter a month name & use the dictionary to tell
them how many days are in the month. 5-6
2. Print out all of the keys in alphabetical order.
3. Print out all of the months with 31 days.
4. Print out the (key – value) pairs sorted by the number of days in
each month.
5. Exit
4 Write a program using function called addict ( dict1, dict2) which
computes the union of two dictionaries. It should return a new dictionary ,
with all the items in both its arguments (assumed to be dictionaries). If the 7
same key appears in both arguments, then pick a value from either of the
two dictionaries.
5 Write a program using a list which contains roll. No., name and marks of
the student. Sort the list in descending order of marks using Selection Sort 8
algorithm.
6 Write a program using function that takes a sorted list and a number as an 9
argument. Search for the number in the sorted list using binary search.
7 Write a program which accept a list containing numbers. Sort the list
using any sorting technique. Thereafter accept a number and display the 10
position where that number is found. Also display suitable message, if the
number is not found in the list.
8 Write a program in Python to implement a stack 11-12
9 Write a program in Python to implement a Queue 13-14
10 Write a program that takes any two lists L & M of the same size & adds
their elements together to form a new list N whose elements are sums of 15
the corresponding elements in L & M. For instance, if L- [3,1,4] and
M=[1,5,9], then N should equal [4,6, 13].
11 Write a program that rotates the elements of a list so that the element at
the first index moves to the second index, the element in the second index 16
moves to the third index, etc., and the element in the last index moves to
the first index.
12 Write a program that interactively creates a nested tuple to store the marks
in three subjects for five students. Also write a function that computes 17-18
total marks & average marks obtained by each student.
13 Write a program using function in Python to count and display the number
of lines starting with alphabet ‘A’ present in a text file “LINES.TXT”. 19
Raise an error if the file is not present.
14 Write a program to count the number of uppercase and lower case 20
alphabets present in a text file “Article.txt”.
15 Write a program to create a CSV file and store empno, name and salary of
employees of an organisation. Run following menu on the file:-
1. Display the data in formatted format
2. Add records
3. Delete data of an employee depending on employee no. 21
4. Modify name of an employee depending on employee no
5. Search an employee on the basis of name and display the data
6. Count number of records
16 Write a program to create a binary file “Result.dat” containing rollno,
name and percentage of students of a class. Then append records in the 22-23
file.
17 Write a program to modify records in the binary file “Result.dat” 24
18 Write a program to display all those records where percentage is greater
than 75% from the binary file “Result.dat”. 25
19 Write a program to delete the third record from the binary file “Result.dat” 26
20 Considering the given tables, write the SQL commands for the given
queries in MySQL.

27-28

I. To create the two tables


II. To add records as given in the tables.
III. To display the names of all white colored vehicles
IV. To display name of vehicle, make and capacity of vehicles in
ascending order of their sitting capacity
V. To display the highest charges at which a vehicle can be hired
from CABHUB.
VI. To display the customer name and the corresponding name of the
vehicle hired by them.
21 Write a program to connect to a database “SPORTS” then store and
display records of a table “PLAYERS”. The structure of the table is :-

29

22 Write a program to search and display data of a given player (on the basis
of name) in the table “PLAYERS” in the database “SPORTS”. If the 30
player is not found then display appropriate message.
23 Write a program to update data of a particular player on the basis of name
of the player in the table “PLAYERS” in the database “SPORTS”. If the 31-32
player does not exist then display appropriate message.
24 Write a program to delete record of a particular player on the basis of
name of the player in the table “PLAYERS” in the database “SPORTS”. If 33
the player does not exist then display appropriate message.
QUESTION-1

Write a menu driven program for the given options using separate functions for each menu option:-

1. To find factorial of a number.


2. To find roots of a quadratic equation
3. To reverse a given number
4. Exit

CODE

def fact(n):
if n ==1 or n == 0:
return 1
fact = 1
for i in range(1,n + 1):
fact *= i
return fact

def root(a, b, c):


root1 = -b + (b ** 2 - 4 * a * c) ** 1 / 2
root2 = -b - (b ** 2 - 4 * a * c) ** 1 / 2
return root1, root2

def rev(n):
rev = ""
num = str(n)
for i in range(len(num) - 1, -1, -1):
rev += num[i]
return int(rev)

# MAIN PROGRAM
choice = 0
while choice != 4:
print()
print("CHOOSE FROM THE GIVEN OPTIONS:-")
print()
print("TYPE 1 TO FIND THE FACTORIAL OF A NUMBER")
print("TYPE 2 TO FIND THE ROOTS OF AN EQUATION ")
print("TYPE 3 TO REVERSE A NUMBER")
print("TYPE 4 TO EXIT THE MENU")
print()
choice = int(input("ENTER YOUR CHOICE: "))
if choice == 1:
print()
num = int(input("ENTER THE NUMBER TO FIND FACTORIAL: "))
print("THE FACTORIAL OF {} IS {}".format(num, fact(num)))
elif choice == 2:
print()
a = int(input("ENTER THE COEFFICIENT OF x^2 : "))
b = int(input("ENTER THE COEFFICIENT OF x : "))
c = int(input("ENTER THE CONSTANT: "))
print()
print("THE ROOTS OF THE EQUATION '{}' ARE '{}'".format(str(a) + 'x^2+' + str(b) + 'x+' + str(c), root(a, b,
c)))
elif choice == 3:
print()
num = int(input("ENTER THE NUMBER TO BE REVERSED: "))
print()
print("THE REVERSE OF THE NUMBER {} IS {}".format(num, rev(num)))
elif choice == 4:
break
else:
print('INVALID CHOICE')

OUTPUT
QUESTION-2
Write a menu driven program for a given string using separate functions for each menu option:-

1. To count number of alphabets, digits and special characters.


2. To count number of words
3. To check whether the string is a palindrome or not
4. Exit

CODE
def count(s):
scount = 0
dcount= 0
spcount = 0
for i in s:
if i.isalpha():
scount += 1
elif i.isdigit():
dcount += 1
else:
spcount += 1
return scount,dcount,spcount

def wcount(s):
a = s.split()
return len(a)

def pcheck(s):
revs = ''
for i in range(len(s)-1,-1,-1):
revs += s[i]
if revs == s:
return 'THE STRING IS A PALINDROME'
else:
return 'THE STRING IS NOT A PALINDROME'

# MAIN PROGRAM

choice = 0
while choice != 4:
print()
print('CHOOSE FROM THE GIVEN OPTIONS:- ')
print('TYPE 1 TO COUNT NUMBER OF ALPHABETS,DIGITS AND SPECIAL CHARACTER.')
print('TYPE 2 TO COUNT NUMBER OF WORDS. ')
print('TYPE 3 TO CHECK WHETHER A STRING IS A PALINDROME OR NOT')
print('TYPE 4 TO EXIT')
print()
choice = int(input('ENTER YOUR CHOICE: '))
if choice == 1:
s = input("ENTER THE STRING: ")
print()
counter = count(s)
print('THE NUMBER OF ALPHABETS,DIGITS AND SPECIAL CHARACTERS IN {} ARE {},{} AND {}
RESPECTIVELY'.format(s,counter[0],counter[1],counter[2]))
elif choice == 2:
s = input('ENTER THE STRING: ')
print('THE NUMBER OF WORDS IN THE STRING ARE {}'.format(wcount(s)))
elif choice == 3:
s = input('ENTER THE STRING: ')
print(pcheck(s))
elif choice == 4:
break
else:
print('INVALID CHOICE')
OUTPUT
QUESTION-3

Create a dictionary whose keys are month names and whose values are the number of days in the
corresponding months. Then run the given menu on the dictionary.

1. Ask the user to enter a month name & use the dictionary to tell them how many days are in
the month.
2. Print out all of the keys in alphabetical order.
3. Print out all of the months with 31 days.
4. Print out the (key – value) pairs sorted by the number of days in each month.
5. Exit

CODE

d = {'JANUARY':31, 'FEBRUARY':28, 'MARCH':31, 'APRIL':30, 'MAY':31, 'JUNE':30, 'JULY':31, 'AUGUST':31,


'SEPTEMBER':30, 'OCTOBER':31, 'NOVEMBER':30, 'DECEMBER':31}
choice = 0
while choice != 5:
print()
print('TYPE 1 TO SEE HOW MANY DAYS ARE THERE IN A MONTH.')
print('TYPE 2 TO SEE ALL THE MONTH NAMES IN ALPHABETICAL ORDER.')
print('TYPE 3 TO SEE ALL THE MONTHS WITH 31 DAYS.')
print('TYPE 4 TO SEE THE NUMBER OF DAYS IN EACH MONTH IN SORTED FORMAT')
print('TYPE 5 TO EXIT')
choice = int(input('ENTER YOUR CHOICE'))
if choice == 1:
mname = input("ENTER MONTH'S NAME: ")
flag = 0
for i in d.keys():
if mname == i:
print('THE NUMBER OF DAYS IN {} ARE {}'.format(mname,d[mname]))
flag = 1
if flag ==0 :
print('NO MONTH FOUND!!!')
if choice == 2:
mnames = []
for i in d.keys():
mnames.append(i)
mnames.sort()
print(mnames)
if choice == 3:
a = []
for i in d.keys():
if d[i] == 31:
a.append(i)
print('THE MONTHS THAT HAVE 31 DAYS ARE ',a)
if choice == 4:
newd= []
for i in d:
if d[i] == 28:
newd += tuple((i,d[i]))
for i in d:
if d[i] == 30:
newd += tuple((i,d[i]))
for i in d:
if d[i]== 31:
newd += tuple((i,d[i]))
print(newd)
OUTPUT
QUESTION-4

Write a program using function called addict ( dict1, dict2) which computes the union of two
dictionaries. It should return a new dictionary , with all the items in both its arguments (assumed to
be dictionaries). If the same key appears in both arguments, then pick a value from either of the two
dictionaries.

CODE

def addict(dict1,dict2):
ndict = {}
for i in dict1:
ndict[i] = dict1[i]
for i in dict2:
if i in ndict:
continue

ndict[i] = dict2[i]
print(ndict)
QUESTION-5

Write a program using a list which contains roll. No., name and marks of the student. Sort the list in
descending order of marks using Selection Sort algorithm.

CODE

A = []
n = int(input('ENTER THE NO OF STUDENTS: '))
for i in range(n):
rno = int(input("ENTER STUDENTS ROLL NO.: "))
name = input("ENETR STUDENT'S NAME: ")
marks = int(input("ENTER MARKS OF STUDENT: "))
A.append([rno,name,marks])

for i in range(len(A)):
min = i
for j in range(i+1,len(A)):
if A[min][2]> A[j][2]:
min = j
A[i],A[min] = A[min],A[i]
# FOR ARRANGING THE LIST IN DESCENDING ORDER
B =[]
for i in range(len(A)-1,-1,-1):
B.append(A[i])
print('THE SORTED LIST:-')
print(B)
OUTPUT
QUESTION-6

Write a program using function that takes a sorted list and a number as an argument. Search for the
number in the sorted list using binary search.

CODE

def binary_search(list, ele):


low = 0
high = len(list) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
if list[mid] < ele:
low = mid + 1
elif list[mid] > ele:
high = mid - 1
else:
return mid
return 'found'
# MAIN PROGRAM
list = []
n = int(input('ENTER THE NO. OF ELEMENTS: '))
for i in range(n):
element = int(input("ENTER THE ELEMENT: "))
list.append(element)
ele = int(input("ENTER THE ELEMENT TO BE SEARCHED: "))
list.sort()
result = binary_search(list, ele)
if result != 'found':
print()
print("Element is present in the list at {} position".format(result+1))
else:
print("Element is not present in list")
OUTPUT
QUESTION-7

Write a program which accept a list containing numbers. Sort the list using any sorting technique.
Thereafter accept a number and display the position where that number is found. Also display
suitable message, if the number is not found in the list.

CODE

n = int(input("ENTER THE NUMBER OF ELEMENTS IN THE LIST: "))


list = []
for i in range(n):
element = int(input("ENTER THE NUMBER: "))
list.append(element)
print('THE LIST IS CREATED.')

ele = int(input('ENTER THE ELEMENT TO BE SEARCHED'))


pos = 0
for i in list:
pos+= 1
if i == ele:
print('THE ELEMENT FOUND AT POSITION {}'.format(pos))
break
else:
print('THE ELEMENT IS NOT IN THE LIST.')
OUTPUT
QUESTION-8

Write a program in Python to implement a stack

CODE

stack = []
def push():
ele = int(input("ENTER THE VALUE OF NEW ELEMENT OF THE STACK: "))
stack.append(ele)
def pop():
top = len(stack)
if top <= 0:
print("STACK UNDERFLOW.")
else:
ele = stack.pop()
print("THE POPED ELEMENT FROM STACK IS",ele)
def display():
top = len(stack)+1
if top <= 1:
print("STACK IS EMPTY")
else:
for i in range(-1,-top,-1):
print(stack[i],end=",")
print()
#MAIN PROGRAM
choice = 1
while choice != 4:
print("1. PUSH AN ELEMENT IS STACK")
print("2. POP AN ELEMENT FROM STACK")
print("3. DISPLAY THE STACK")
print("4. EXIT THE PROGRAM")

choice = int(input("ENTER CHOICE: "))


if choice == 1:
push()
elif choice == 2:
pop()
elif choice == 3:
display()
elif choice == 4:
print("END OF STACK")
break
else:
print('INVALID CHOICE!!!')
OUTPUT
QUESTION-9

Write a program in Python to implement a Queue

CODE

queue = []
def insert():
ele = int(input("ENTER THE VALUE: "))
queue.append(ele)
def delete():
length = len(queue)
if length<= 0:
print("QUEUE UNDERFLOW.")
else:
print("THE DELETED ELEMENT IS",queue[0])
del queue[0]
def display():
length = len(queue)
if length <= 0:
print("QUEUE UNDERFLOW.")
else:
for i in range(length):
print(queue[i],end=',')
print()
# MAIN PROGRAM
choice = 1
while choice!= 4:
print("1. INSERT AN ELEMENT")
print("2. DELETE AN ELEMENT")
print("3. DISPLAY THE QUEUE")
print("4. EXIT")

choice = int(input("ENTER YOUR CHOICE: "))


if choice ==1:
insert()
elif choice == 2:
delete()
elif choice == 3:
display()
elif choice == 4:
print("END OF QUEUE")
else:
print("INVALID CHOICE")
OUTPUT
QUESTION-10

Write a program that takes any two lists L & M of the same size & adds their elements together to
form a new list N whose elements are sums of the corresponding elements in L & M. For instance, if
L- [3,1,4] and M=[1,5,9], then N should equal [4,6, 13].

CODE

L =[]
M =[]
n = int(input("ENTER THE NUMBER OF ELEMENTS IN THE LIST: "))
for i in range(n):
element = int(input("ENTER THE NUMBER: "))
L.append(element)
print('THE LIST "L" IS CREATED.')

for i in range(n):
element = int(input("ENTER THE NUMBER: "))
M.append(element)
print('THE LIST "M" IS CREATED.')

N= []
for i in range(n):
N.append(L[i]+M[i])
print()
print("THE REQUIRED LIST IS:-")
print(N)
OUTPUT
QUESTION-11

Write a program that rotates the elements of a list so that the element at the first index moves to the
second index, the element in the second index moves to the third index, etc., and the element in the
last index moves to the first index.

CODE

l = []
n = int(input("ENTER THE NO. OF ELMENT IN THE LIST: "))
for i in range(n):
ele = input("ENTER THE ELEMENT: ")
l.append(ele)
m = []
for i in range(-1,n-1):
m.append(l[i])
print("THE ORIGINAL LIST IS,-")
print(l)
print("THE LIST AFTER ROTATION,-")
print(m)
OUTPUT
QUESTION-12

Write a program that interactively creates a nested tuple to store the marks in three subjects for five
students. Also write a function that computes total marks & average marks obtained by each student.

CODE

def sum_marks():
for i in t:
sum =0
for j in i:
sum+= j
print('THE SUM OF MARKS OF STUDENTS IS ',sum)

def avg_marks():
for i in t:
sum =0
for j in i:
sum+= j
print('THE AVERAGE OF MARKS IS {}.'.format(sum/3))

t = tuple()
student = 0
for i in range(5):
st = tuple()
for i in range(1,4):
ele = int(input('ENTER THE MARKS IN SUBJECT{}: '.format(i)))
st += (ele,)
student += 1
print('THE MARKS OF STUDENT{} ARE REGISTERED'.format(student))
t += (st,)

#MAIN PROGRAM
choice = 0
while choice != 3:
print()
print('TYPE 1 TO FIND THE SUM OF MARKS OF STUDENTS.')
print("TYPE 2 TO FIND THE AVERAGE OF MARKS OF STUDENTS.")
print("TYPE 3 TO EXIT.")
choice = int(input("ENTER YOUR CHOICE: "))
if choice == 1:
sum_marks()
elif choice == 2:
avg_marks()
elif choice == 3:
break
else:
print("INVALID CHOICE")
OUTPUT
QUESTION-13

Write a program using function in Python to count and display the number of lines starting with
alphabet ‘A’ present in a text file “LINES.TXT”. Raise an error if the file is not present.

CODE

def character_count():
required = []
count= 0
try:
file = open("LINES.TXT",'r')
data = file.readlines()
for i in data:
if i[0] == 'A':
count += 1
required.append(i)
print('THE NUMBER OF LINES STARTING WITH "A" IS {}'.format(count))
print()
print("THE LINES ARE AS FOLLOWS:-")
for i in required:
print(i,end="")
file.close()
except:
print("THE FILE IS NOT FOUND!!!")
character_count()
OUTPUT
QUESTION-14

Write a program to count the number of uppercase and lower case alphabets present in a text file
“Article.txt”.

CODE

def character_count():
try:
ucount = 0
lcount = 0
file = open("Article.TXT",'r')
data = file.read()
for i in data:
if i.isupper():
ucount += 1
elif i.islower():
lcount += 1
print("THE NUMBER OF UPPER ALPHABETS IN 'ARTICLE.TXT' IS {}".format(ucount))
print("THE NUMBER OF LOWER ALPHABETS IN 'ARTICLE.TXT' IS {}".format(lcount))
file.close()
except:
print("THE FILE NOT FOUND!!!")
#MAIN PROGRAM
character_count()
OUTPUT
QUESTION-15

Write a program to create a CSV file and store empno, name and salary of employees of an
organisation. Run following menu on the file:-

1. Display the data in formatted format


2. Add records
3. Delete data of an employee depending on employee no.
4. Modify name of an employee depending on employee no
5. Search an employee on the basis of name and display the data
6. Count number of records

CODE

import csv
entry = ' '
while entry != 'NO':
file = open("EMPLOYEE.csv",'a')
writer = csv.writer(file)
EID = int(input("ENTER EMPLOYEE ID: "))
ENAME = (input("ENTER NAME OF EMPLOYEE: "))
ESAL = int(input("ENTER SALARY OF EMPLOYEE: "))
writer.writerow([EID,ENAME,ESAL])
print("RECORD ADDITION SUCCESSFUL")
print()
entry = input("ENTER 'YES' TO CONTINUE OR ELSE 'NO'")

OUTPUT
QUESTION-16

Write a program to create a binary file “Result.dat” containing rollno, name and percentage of
students of a class. Then append records in the file.

CODE

import pickle
def write():
f= open("result.dat", 'wb')
record = []
while True:
rno= int(input("Enter roll no.:"))
name= input("Enter name:")
marks = int(input("Enter marks:"))
data = [rno, name, marks]
record.append(data)
ch = input("Do you want to enter more records? (y/n)")
if ch=='n' or ch =='N':
break
pickle.dump(record,f)
f.close()
def read():
f = open("result.dat", 'rb')
s = pickle.load(f)
for i in s:
print(i)

def append():
f= open("result.dat", 'wb')
record = []
while True:
rno= int(input("Enter roll no.:"))
name= input("Enter name:")
marks = int(input("Enter marks:"))
data = [rno, name, marks]
record.append(data)
ch = input("Do you want to enter more records? (y/n)")
if ch=='n' or ch =='N':
break
pickle.dump(record,f)
f.close()

print("Press 1 to enter new records")


print("Press 2 to append existing records")
print("Press 3 to view records")
a=int(input())
if a==1:
write()
elif a==2:
append()
elif a==3:
read()
else:
print("invalid choice" ,'\n', "program ended")

OUTPUT
QUESTION-17

Write a program to modify records in the binary file “Result.dat”

CODE

import pickle
def modify():
f= open("result.dat", 'wb')
record = []
while True:
rno= int(input("enter roll no.:"))
name= input("enter name:")
marks = int(input("enter marks:"))
data = [rno, name, marks]
record.append(data)
ch = input("do you want to enter more records? (y/n)")
if ch=='n' or ch =='N':
break
modify()
OUTPUT
QUESTION-18

Write a program to display all those records where percentage is greater than 75% from the binary
file “Result.dat”.

CODE

import pickle
def ABOVE_75():
f = open("result.dat", 'rb+')
s = pickle.load(f)
l = len(s)
del s[2]
pickle.dump(s,f)
print(s)
f.close()
ABOVE_75()
QUESTION-19

Write a program to delete the third record from the binary file “Result.dat”

CODE

import pickle
def DELETE_THIRD_ROW():
global s
f = open("result.dat", 'rb')
s = pickle.load(f)
l = len(s)
if len(s) < 3:
print("Third row doesnt exist")
else:
del s[2]
print("Third row succesfully deleted")
new = open("result.dat", 'wb')
pickle.dump(s,new)
new.close()
DELETE_THIRD_ROW()
QUESTION-20

Considering the given tables, write the SQL commands for the given queries in MySQL.

I. To create the two tables


II. To add records as given in the tables.

III. To display the names of all white colored vehicles


IV. To display name of vehicle, make and capacity of vehicles in ascending order of their sitting
capacity
V. To display the highest charges at which a vehicle can be hired from CABHUB.
VI. To display the customer name and the corresponding name of the vehicle hired by them.

ANSWERS

I. CREATE TABLE CARHUB(‘VCode’ int primary key,’VehicleName’ varchar(20), ‘Make’


varchar(20) ,’Color’ varchar(20) , ‘Capacity’ int(2), ‘Charges’ int(2) );

CREATE TABLE CUSTOMER(‘CCode’ int primary key, ‘CName’ varchar(20), ‘VCode’


varchar(3));

II. INSERT INTO CARHUB(‘100’,’Innova’,’Toyota’,’WHITE’,’7’,’15’);


INSERT INTO CARHUB(‘102’,’SX4’,’Suzuki’,’BLUE’,’4’,’14’);
INSERT INTO CARHUB(‘104’,’C Class’,’Mercedes’,’RED’,’4’,’35’);
INSERT INTO CARHUB(‘105’,’A-Star’,’Suzuki’,’WHITE’,’3’,’14’);
INSERT INTO CARHUB(‘108’,’Indigo’,’Tata’,’SILVER’,’3’,’12’);

INSERT INTO CUSTOMER(‘1’,’Hemant Sahu’,’101’);


INSERT INTO CUSTOMER(‘2’,’Raj Lal’,’108’);
INSERT INTO CUSTOMER(‘3’,’Feroza Shah’,’105’);
INSERT INTO CUSTOMER(‘4’,’Ketan Dhal’,’104’);
III. SELECT VehicleName FROM CARHUB WHERE Color=’WHITE’;

IV. SELECT VehicleName , Make , Capacity FROM CARHUB ORDER BY ‘Capacity’;

V. SELECT MAX(Charges) FROM CRAHUB;

VI. SELECT CUSTOMER.CName , CARHUB.VehicleName FROM CARHUB , CUSTOMER


WHERE CARHUB.VCode = CUSTTOMER.VCode ;
QUESTION-21

Write a program to connect to a database “SPORTS” then store and display records of a table
“PLAYERS”. The structure of the table is :-

CODE

import mysql.connector
mydb = mysql.connector.connect(host="localhost",
user="root",password="abcd@1234",database="SPORTS")
mycur = mydb.cursor()

mycur.execute("INSERT INTO PLAYER VALUES('1','Nabi Ahmad','101')")


mycur.execute("INSERT INTO PLAYER VALUES('2','Ravi Sahai','108')")
mycur.execute("INSERT INTO PLAYER VALUES('3','Jatin','101')")
mycur.execute("INSERT INTO PLAYER VALUES('4','Nazneen','103')")
mydb.commit()
QUESTION-22

Write a program to search and display data of a given player (on the basis of name) in the table
“PLAYERS” in the database “SPORTS”. If the player is not found then display appropriate message.

CODE

import mysql.connector
mydb = mysql.connector.connect(host="localhost",
user="root",password="abcd@1234",database="SPORTS")
mycur = mydb.cursor()
mycur.execute("SELECT * FROM PLAYER")

search = input("ENTER THE NAME OF THE PLAYER TO BE SEARCHED: ")


flag = 0
for i in mycur:
if search == i[1]:
print("THE PLAYER DETAILS ARE AS FOLLOWS,-")
print('PCode','Name','Gcode',sep= '\t')
print(i)
flag = 1
if flag == 0:
print("THE PLAYER NAMED '{}' IS NOT IN THE DATABASE.".format(search))

OUTPUT
QUESTION-23

Write a program to update data of a particular player on the basis of name of the player in the table
“PLAYERS” in the database “SPORTS”. If the player does not exist then display appropriate
message.

CODE

import mysql.connector
mydb = mysql.connector.connect(host="localhost",
user="root",password="abcd@1234",database="SPORTS")
mycur = mydb.cursor()
mycur.execute("SELECT * FROM PLAYER")

search = input("ENTER THE NAME OF THE PLAYER TO BE SEARCHED: ")


flag = 0
for i in mycur:
if search == i[1]:
choice = 1
while choice!= 3:
print("1. TO UPDATE THE PCode OF THE PLAYER")
print("2. TO UPDATE THE Gcode OF THE PLAYER")
print("3. EXIT")
choice = int(input("ENTER YOUR CHOICE: "))
if choice == 1:
npcode = input("ENTER THE NEW PCode: ")
cmd = "UPDATE PLAYER SET PCode = '{}' WHERE Name ='{}'".format(npcode,i[1])
mycur.execute(cmd)
mydb.commit()
print('UPDATION SUCCESSFUL')
elif choice == 2:
ngcode = input("ENTER THE NEW GCode FOR THE PLAYER: ")
cmd = "UPDATE PLAYER SET Gcode ='{}' WHERE Name ='{}'".format(ngcode,i[1])
mycur.execute(cmd)
mydb.commit()
print('UPDATION SUCCESSFUL')
flag = 1
if flag == 0:
print("THE PLAYER NAMED '{}' IS NOT IN THE DATABASE.".format(search))
OUTPUT
QUESTION -24

Write a program to delete record of a particular player on the basis of name of the player in the table
“PLAYERS” in the database “SPORTS”. If the player does not exist then display appropriate
message.

CODE

import mysql.connector as conn


mydb = conn.connect(host = "localhost",user = "root", passwd = "abcd@1234", database = "SPORTS")
mycursor = mydb.cursor()

def deleting_student():
delet1 = str(input("ENTER NAME OF THE PLAYER"))
f = mycursor.execute("SELECT Name FROM PLAYERS")
flag=0
for i in mycursor:
for j in i:
if j== delet1:
flag=1
if flag==1:
print("we found the data of the player you want to delete")
print("the following data will be deleted")
h = mycursor.execute("select * from PLAYERS where Name='{}'".format(delet1))
for i in mycursor:
print(i)
print("are your sure you want to proceed? (yes/no)")
confirmation=0
confirmation=str(input())
if confirmation=="yes":
mycursor.execute("delete from STUDENTS where Name='{}'".format(delet1))
mydb.commit()
print("deletion succesful")
elif confirmation=="no" or "NO":
print("deletion stopped")
else:
print("invalid choice ")
else:
print("player name not found")
mydb.commit()

You might also like