CS - Practical File 1
CS - Practical File 1
11. Display the Cust_Name and Loan_Amount for all the loans which do not have number of
instalments 36.
12. Display the Cust_Name and Loan_Amount for all the loans for which the loan amount is less
than 500000 or int_rate is more than 12.
13. Display the details of all the loans whose Loan_Amount is in the range 400000 to 500000.
14. Display the Cust_Name and Loan_Amount for all the loans for which the number of
instalments are 24, 36, or 48. (Using IN operator)
15. Display the details of all the loans whose rate of interest is in the range 11% to 12%.
16. Display the AccNo, Cust_Name, and Loan_Amount for all the loans for which the
Cust_Name contains 'a'
17. Display the AccNo, Cust_Name, and Loan_Amount for all the loans for which the
Cust_Name does not contain 'P'.
18. Display the details of all the loans in the ascending order of their Loan_Amount and within
Loan_Amount in the descending order of their Start_Date.
19. Put the interest rate 11.50% for all the loans for which interest rate is NULL.
20. Delete the records of all the loans whose start date is before 2008.
21. Add another column Category of type CHAR(1) in the Loans_Accounts table.
MySQL Lab Exercise 2
(i) Display the lowest and the highest classes from the table STUDENTS.
(ii) Display the number of students in each class from the table STUDENTS.
(vi)Display the name and phone numbers of the students of class 12 who are play some game.
(viii) Display the names and phone numbers of the students whose grade is ‘A’ and whose
coach is Narendra.
Practical file questions
1. Write a menu driven program to accept a string from the user and perform the following on it
using functions: • Reverse • replace ‘s’ or ‘S’ with “#” • Find the repeating characters in the string
• Encode the string by adding 2 to each ASCII value
def rev(a):
print(a[-1::-1])
def rep(a):
print(a.replace('s', '#').replace('S', '#'))
def findrep(a):
l = []
for i in a:
if a.count(i) > 1 and i not in l:
l.append(i)
print("The repeating elements are:", end=" ")
if len(l) > 0:
for j in range(len(l) - 1):
print(l[j], end=",")
print(l[-1])
else:
print("None")
def encode(a):
s = ''
for i in a:
s += (chr(ord(i) + 2))
print("Encoded string is:", s)
print('''Choose an option from the following:
1---Reverse the string
2---Replace ‘s’ or ‘S’ with “#”
3---Find the repeating elements
4---Encode the string
''')
str1 = input("Enter a String Value: ")
ch = int(input("Enter your choice: "))
if ch == 1:
rev(str1)
elif ch == 2:
rep(str1)
elif ch == 3:
findrep(str1)
elif ch == 4:
encode(str1)
else:
print("Invalid Choice")
2. Write a program to create a dictionary containing names of books as keys and authors as
values.
D1 = {}
n = int(input("Enter the No. of Books to be Added: "))
print()
for i in range(n):
k = input("Enter the Book Name: ")
v = input("Enter the Author Name: ")
print()
D1[k] = v
print(D1)
3. Write a program that receives two numbers in a function and returns the results of all
arithmetic operations on these numbers
4. Write a function in Python to find and display the prime numbers between 2 to N. Pass N as
an argument to the function.
def findprim(a):
p = []
for j in range(2, a + 1):
l = []
for i in range(1, j + 1):
if j % i == 0:
l.append(i)
if len(l) == 2:
p.append(j)
for k in range(len(p) - 1):
print(p[k], end=",")
print(p[-1])
N = int(input("Enter a No.: "))
print("Prime No.s from 2 to", N, ":", end=" ")
findprim(N)
5. Write a function fiveEnding(SCORES) to add all those values in the list of SCORES,which are
ending with five(5) and display the sum.
def fiveEnding(SCORES):
s=0
for i in SCORES:
if i % 10 == 5:
s += i
print("The sum of all the numbers ending with 5 is:", s)
SCORES = []
n = int(input("Enter no. of values: "))
print()
for j in range(n):
a = int(input("Enter a value: "))
SCORES.append(a)
print()
fiveEnding(SCORES)
6. Assuming that a text file named practical.txt contains some text written into it, write a function
that reads the file practical.txt and creates a new file named response.txt, to contain only those
words from the file practical.txt which have 5 characters. For example if the file practical.txt
contains Carry umbrella and overcoat when it rains Then the file response.txt shall contain
Carry rains
def words_of_length(s):
t=f.read().replace("\n"," ")
l=t.split(" ")
n=open("response.txt","w")
for i in l:
if len(i)==s:
n.write(i)
n.write(' ')
f=open("practical.txt",'r')
words_of_length(5)
7. Write a menu driven program to add, and display data from a text file. The text file contains
bank details (Account number, name and balance).
while True:
print('''
Menu:
1> Add Data
2> View Data
3> Exit
''')
user_input = int(input("Enter your choice: "))
if user_input == 1:
f=open("Bank Detais.txt","a")
while True:
acc_no = int(input("Enter your account number: "))
name = input("Enter your account holder name: ")
balance = int(input("Enter your account balance: "))
f.write(str(acc_no)+" "+name+" "+str(balance)+"\n")
cont = input("Do you want to add more data (y/n): ")
if cont == "n":
break
if user_input == 2:
f=open("Bank Detais.txt","r")
while True:
rec=f.readline().split()
print()
print("Account Number:",rec[0])
print("Account Holder Name:",rec[1])
print("Account Balance:",rec[2])
print()
cont = input("Do you want to display more data (y/n): ")
if cont == "n":
break
if user_input == 3:
print("Thank you for using our banking system.")
break
8. Write a menu-driven program, to create a Phonebook Directory(Phonebook.txt) using
different functions. The functions have to created for the following features of the Phonebook
Directory: • Storing the Contact Numbers of People • Searching for the Contact Number using
the person's name • Displaying the data in the Directory • Updating the persons Contact number
using the person’s name
def add_cont(name,number):
f=open("Phonebook.txt","a")
f.write(name+" -- "+number+"\n")
f.close()
def search_cont(NM):
re=open("Phonebook.txt","r")
for i in re.readlines():
lst=i.split(' -- ')
if lst[0]==NM:
for j in lst:
print(j,end=" ")
re.close()
def display_cont():
d=open("Phonebook.txt","r")
for i in d.readlines():
print(i)
d.close()
def update_cont(NM,NN):
PF=open("Phonebook.txt","r")
rec=PF.readlines()
lst=[]
lst1=[]
k=0
for i in rec:
lst.append(i.split(' -- '))
for i in range(0,len(lst),2):
lst1.append(lst[i])
for i in lst1:
if i==NM:
break
k+=1
rec[k]=(NM+" -- "+str(NN)+"\n")
NF=open("Phonebook.txt","w")
NF.writelines(rec)
PF.close()
NF.close()
while True:
print('''
Phonebook Directory Menu:
1> Add a new contact
2> Search for a contact
3> Displaly all contacts
4> Update a contact
5> Exit
''')
choice=int(input("Enter your choice: "))
if choice==1:
name=input("Enter the Full Name: ")
number=input("Enter the Number: ")
add_cont(name,number)
elif choice==2:
name=input("Enter the Full Name: ")
search_cont(name)
elif choice==3:
display_cont()
elif choice==4:
name=input("Enter the Full Name: ")
number=input("Enter the Number: ")
update_cont(name,number)
elif choice==5:
print("Program Ended.")
break
9. A binary file "Book.dat" has structure [BookNo, Book_Name, Author, Price]. • Write a user
defined function createFile() to input data for a record and add to Book.dat. • Write a function
countRec(Author) in Python which accepts the Author name as parameter and count and return
number of books by the given Author are stored in the binary file "Book.dat". • Write a function
deldata() to delete the record from the file for the BookNo entered by the user.
def createFile():
f=open("Book.dat","ab")
while True:
BR=[]
bno=int(input("Enter Book Number: "))
bnm=input("Enter Book Name: ")
bau=input("Enter Author Name: ")
bpr=int(input("Enter Price: "))
BR=[bno,bnm,bau,bpr]
dump(BR,f)
ch=input("Do you want to enter more records? (y/n): ")
if ch.lower()=="n":
break
f.close()
def countRec(author):
f=open("Book.dat","rb")
c=0
try:
while True:
rec=load(f)
if rec[2]==author:
c+=1
except EOFError:
pass
print("Number of books by",author,"is",c)
f.close()
def deldata(n):
recs=[]
d=open("Book.dat","rb")
try:
while True:
rec=load(d)
if rec[0]!=n:
recs.append(rec)
except EOFError:
pass
d.close()
d=open("Book.dat","wb")
for i in recs:
dump(i,d)
d.close()
createFile()
countRec('J.K.Rowling')
deldata(2)
10 . Write a program to show all the tables that exist in MySQL using Python Interface
import mysql.connector
conn =
mysql.connector.connect(host='localhost',user='root',password='sqllog',database='loans')
c.conn.cursor()
c.execute("SHOW TABLES")
for i in c:
print(i)
11. Write a program to check for all the databases, present in MySQL using Python
import mysql.connector
conn =
mysql.connector.connect(host='localhost',user='root',password='sqllog',database='loans')
c.conn.cursor()
c.execute("SHOW DATABASES")
for i in c:
print(i)
12. Write a program to insert multiple records onto mysql table Employee using Python and also
display all the records present in the table.
import mysql.connector
conn =
mysql.connector.connect(host='localhost',user='root',password='sqllog',database='loans')
c=conn.cursor()
n=int(input("Enter No. of records to be entered: "))
recs=[]
for i in range(n):
print()
eid=int(input("Enter Emp. I.D: "))
nm=input("Enter Name: ")
des=input("Enter Designation: ")
doj=input("Enter Date (YYYY-MM-DD): ")
sal=float(input("Enter Salary: "))
com=float(input("Enter Commission: "))
recs.append((eid,nm,des,doj,sal,com))
c.executemany("INSERT INTO Employee (EmpID, EMPName, Designation, DOJ, Sal, comm)
VALUES(%s,%s,%s,%s,%s,%s)",recs)
conn.commit()
c.execute("SELECT * FROM Employee")
for i in c:
print(i)
13. Create a menu driven application with options add modify delete and display data from
MySQL table Customer with fields accno, name, balance, mobno and emailID.
import mysql.connector
conn =
mysql.connector.connect(host="localhost",user="root",password="sqllog",database='loans')
c=conn.cursor()
while True:
print('''
MENU:
1> Add
2> Modify
3> Delete
4> Display
5> Exit
''')
if ch==2:
a=int(input("Enter Account No.: "))
print('''
Select The Field to be Changed:
1> Account No.
2> Name
3> Balance
4> Mobile No.
5> Email_ID
''')
f=int(input("Enter Your Choice: "))
fields=('AccNo','Name','Balance','MobNo','EmailID')
if f<=4 and f!=2:
nv=int(input("Enter Updated Value: "))
else:
nv=input("Enter Updated Value: ")
query="UPDATE Customer SET {} = %s WHERE AccNo=%s".format(fields[f-1])
c.execute(query,(nv,a))
conn.commit()
print("Detail Updated.")
if ch==3:
a=int(input("Enter Account No.: "))
c.execute("DELETE FROM Customer WHERE AccNo=%s",(a,))
conn.commit()
if ch==4:
c.execute("SELECT * FROM Customer")
for i in c:
print("Acc_No.:",i[0])
print("Name:",i[1])
print("Balance:",i[2])
print("Mob_No.:",i[3])
print("Email_ID:",i[4])
print()
print()
if ch==5:
break