Practicle File CS 2022 23
Practicle File CS 2022 23
Practicle File CS 2022 23
27-28
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:-
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 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:-
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
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
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
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")
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")
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:-
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()
OUTPUT
QUESTION-17
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.
ANSWERS
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()
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")
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")
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
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()