Q1: Write a python program to print prime numbers between the given limits.
Prime Number: Prime numbers are whole numbers greater than 1, that have only
two factors 1 and the number itself.
Source Code:
def series(lower,upper):
print("Prime numbers between", lower, "and", upper, "are:")
num=lower
while(num<=upper):
c=0
# check for factors
for i in range(1,num+1):
if (num % i) == 0:
c=c+1
if(c==2):
print(num,"is a prime number")
num=num+1
lower=int(input("Enter Lower limit of the series"))
upper=int(input("Enter Upper limit of the series"))
1
Output:
2
Q2: Write a python program to enter a numeric list and pint all Kaprekar number
between the limit.
Kaprekar number for a given base is a non-negative integer, the representation of
whose square in that base can be split into two parts—either or both of which
may include leading zeroes—that add up to the original number. For instance, 45
is a Kaprekar number, because 452 = 2025 and 20 + 25 = 45.
Source Code:
def limit(lower,upper):
for i in range(lower,upper+1):
if(kaprekar(i)==i):
print(i)
def kaprekar(n):
s=str(n**2)
s1=""
s2=""
if(len(s)%2==0):
s1=int(s[0:len(s)//2])
s2=int(s[len(s)//2:])
if(s1+s2==n):
return n
else:
if((int(s[0:len(s)//2])+int(s[len(s)//2+1:]))==n):
return n
lower=int(input("Enter the lower limit"))
upper=int(input("Enter upper limit"))
limit(lower,upper)
3
Output :
4
Q3. Write a Python Program to check whether the given no. is
Automorphic number
Neon Number by menu driven program
Automorphic Number: An Automorphic number is a number whosesquare ends
with the sane digits as the original number
25=25*25=625
Neon Number: A Neon number is a number where the sum of digits of square of
the number is equal to the number.
9=9*9=81=8+1=9
Source Code:
def automorphic(n):
x=n*n
l=len(str(n))
last=x%pow(10,l)
if (last==n):
print(n,"is Automorphic Number")
else:
print(n,"is not a Automorphic Number")
def neon(n):
x=n*n
sum=0
while (x>0):
y=x%10
sum=sum+y
x=x//10
if (sum==n):
print(n,"is Neon Number")
5
else:
print(n,"is not a Neon Number")
n=int(input("Enter any Number="))
print("1.Check Automorphic Number")
print("2.Check Neon Number")
ch=int(input("Enter your Choice="))
if (ch==1):
automorphic(n)
elif(ch==2):
neon(n)
6
Output :
7
Q4. Extract two tuple slices out of given tuple of numbers. Display and print the
sum of elements of first tuple slice which contain every other element of the
tuple between indexes 5 to 15. Program should also display the average of
elements in second tuple slice that contains every fourth element of the list.
Source Code:
t=(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20)
slice1=t[5:15:2]
slice2=t[::4]
sum=0
avg=0
print("Elements of first Slice:")
for a in slice1:
sum=sum+a
print(a,end=',')
print("\n Sum of elements of slice 1=",sum)
sum=0
print("\n")
print("Elements of second Slice:")
for a in slice2:
sum=sum+a
print(a,end=',')
avg=sum/len(slice2)
print("\n Average of elements of slice 2=",avg)
8
Output :
9
Q5. Write a program to check whether the given string is Palindrome or not.
Source Code :
def palindrome():
length=len(string)
mid=int(length/2)
rev=-1
for a in range(mid):
if string[a]==string[rev]:
a=a+1
rev=rev-1
else:
print(string,"is not palindrome")
break
else:
print(string,"is palindrome")
string=input("Enter any string=")
palindrome()
10
Output :
11
Q6 :Write a python program to insert small paragraph and count the frequency
of each vowel present in it.
Source Code:
def count(arr, x):
print("Frequancy of each vowels")
print("Vowels------------Frequency")
for i in range(len(arr)):
c=0
for j in x:
if arr[i] == j:
c=c+1
print(arr[i],"----------------",c)
arr = ['a','e','i','o','u','A','E','I','O','U']
str=input("Enter sentance")
print("element found at index ",count(arr,str))
12
Output:
13
Q7: Write a python program to enter a numeric list and search a number in the
entered list if it is in the list then display “search successful. Number is in the
list” otherwise display “Number is not in the list”.
Source Code:
def search(numlist,number):
f=0
for i in range(len(numlist)):
if numlist[i]== number :
f=1
if(f==0):
print("number is not in the list")
else:
print("Search Successful")
print("number is in the list")
maxrange =int(input("Enter Count of numbers:"))
Lst1=list()
for i in range(0, maxrange):
Lst1.append(int(input("Enter list item")))
number=int(input("Enter number which you want to search :"))
search(Lst1,number)
14
Output :
15
Q8. A dictionary contains details of two workers with their names as keys and
other details in the form of values.WAP using function to
Print worker’s information in records format
Update and print the dictionary with third worker detail.
Count no. of employees
Sort the dictionary with keys
Source Code:
def update_emp():
employees.update({"Riya":{"age":25,"salary":15000}})
print("\n")
print("Updated Employee details")
print("************************")
for key in employees:
print("Employee Name :",key)
print("Age :",str(employees[key]["age"]))
print("Salary :",str(employees[key]["salary"]))
def count_emp():
count=len(employees)
print("\n")
print("Numner of Employees")
print("*******************")
print(count)
def sort_key():
print("\n")
print("Sorted list with keys")
print("*********************")
print(sorted(employees.keys()))
employees ={"Rohan":{"age":24,"salary":10000},"Divya":{"age":22,"salary":12000}}
print("Worker's information in records format")
print("**************************************")
for key in employees:
print("Employee Name :",key)
print("Age :",str(employees[key]["age"]))
print("Salary :",str(employees[key]["salary"]))
update_emp()
count_emp()
sort_key() 16
Output:
17
Q9: Write a python program to read a file named “story.txt”, count and print total
words starting with “a” or “A” in the file?
Source Code:
def count_words():
w=0
s=0
f=open("read.txt")
lines=f.readlines()
for word in lines:
s=s+1
print(s,"-",word)
if(word[0]=="t" or word[0]=="T"):
w=w+1
print("Total lines starting with 'T' are ",w)
print("Total number of lines are ",s)
# function calling
count_words()
18
Output:
19
Q10: Write a python program to read a file named “article.txt”, count and print
the following:
(i) length of the file(total characters in file)
(ii)total alphabets
(iii) total upper case alphabets
(iv) total lower case alphabets
(v) total digits
(vi) total spaces
(vii) total special character
Source Code:
def count():
a=0
ua=0
la=0
d=0
sp=0
spl=0
with open("read.txt") as f:
while True:
c=f.read(1)
if not c:
break
print(c,end='')
if((c>='A' and c<='Z') or (c>='a' and c<='z')):
a=a+1
if((c>='A' and c<='Z') or (c>='a' and c<='z')):
if(c>='A' and c<='Z'):
ua=ua+1
else:
la=la+1
elif(c>='0' and c<='9'):
d=d+1
elif(c==' '):
sp=sp+1
else:
spl=spl+1
print("total alphabets ",a)
print("total upper case alphabets ",ua)
print("total lower case alphabets ",la)
print("total digits ",d)
20
print("total spaces ",sp)
print("total special characters ",spl)
# function calling
count( )
21
___________________________________________________________
Output:
22
Q11: Write a python program to read and write employee record into the binary
file.
Source Code:
def writedata():
print("WORKING WITH BINARY FILES")
bfile=open("empfile.dat","ab")
recno=1
print ("Enter Records of Employees")
print()
#taking data from user and dumping in the file as list object
while True:
print("RECORD No.", recno)
eno=int(input("\tEmployee number : "))
ename=input("\tEmployee Name : ")
ebasic=int(input("\tBasic Salary : "))
allow=int(input("\tAllowances : "))
totsal=ebasic+allow
print("\tTOTAL SALARY : ", totsal)
edata=[eno,ename,ebasic,allow,totsal]
pickle.dump(edata,bfile)
ans=input("Do you wish to enter more records (y/n)? ")
recno=recno+1
if ans.lower()=='n':
print("Record entry OVER ")
print()
break
# retrieving the size of file
print("Size of binary file (in bytes):",bfile.tell())
bfile.close()
def readdata():
# Reading the employee records from the file using load() module
print("Now reading the employee records from the file")
print()
readrec=1
try:
with open("empfile.dat","rb") as bfile:
while True:
edata=pickle.load(bfile)
print("Record Number : ",readrec)
23
print(edata)
readrec=readrec+1
except EOFError:
pass
bfile.close()
writedata()
readdata()
24
Output:
25
Q12: Write a menu driven program in Python that asks the user to add, display,
and search records of employee stored in a binary file. The em
ployee record contains employee code, name and salary. It should be stored in
a list object. Your program should pickle the object and save it to a binary file.
_____________________________________________________________
Source Code:
import pickle
def set_data():
empcode = int(input('Enter Employee code: '))
name = input('Enter Employee name: ')
salary = int(input('Enter salary: '))
print()
#create a list
employee = [empcode,name,salary]
return employee
def display_data(employee):
print('Employee code:', employee[0])
print('Employee name:', employee[1])
print('Salary:', employee[2])
print()
def write_record():
#open file in binary mode for writing.
outfile = open('emp.dat', 'ab')
#serialize the object and writing to file
pickle.dump(set_data(), outfile)
#close the file
outfile.close()
def read_records():
#open file in binary mode for reading
infile = open('emp.dat', 'rb')
#read to the end of file.
while True:
26
try:
#reading the oject from file
employee = pickle.load(infile)
#display the object
display_data(employee)
except EOFError:
break
#close the file
infile.close()
def search_record():
infile = open('emp.dat', 'rb')
empcode = int(input("Enter employee code to search:"))
flag = False
#read to the end of file.
while True:
try:
#reading the object from file
employee = pickle.load(infile)
#display record if found and set flag
if employee[0] == empcode:
display_data(employee)
flag = True
break
except EOFError:
break
if flag == False:
print('Record not Found')
print()
#close the file
infile.close()
def show_choices():
print('Menu')
print('1. Add Record')
print('2. Display Records')
print('3. Search a Record')
print('4. Exit')
27
def main():
while(True):
show_choices()
choice = input('Enter choice(1-4): ')
print()
if choice == '1':
write_record()
elif choice == '2':
read_records()
elif choice == '3':
search_record()
elif choice == '4':
break
else:
print('Invalid input')
#call the main function
main()
28
Output:
29
Q13: Write a menu driven program in Python that asks the user to add, display,
and search records of student stored in a CSV file. The student
record contains student name, branch,year,CGPA. It should be stored in a list
object. Your program should write the object and save it to a CSV file.
Source Code:
def create():
# importing the csv module
import csv
# writing to csv file
csvfile=open("details.csv", 'w')
obj=csv.writer(csvfile)
record=['Name','Branch','Year','CGPA']
obj.writerow(record)
while True:
name=input("enter name")
branch=input("enter Branch")
year=input("enter Year")
cgpa=input("enter CGPA")
record=[name,branch,year,cgpa]
obj.writerow(record)
ch=int(input("Enter Your choice\n 1: Enter More Record\n 2: Exit"))
if(ch==2):
break
def display():
# importing the csv module
import csv
csvfile=open("details.csv",'r')
fobj=csv.reader(csvfile)
for i in fobj:
print(i)
def search():
# importing the csv module
import csv
csvfile=open("details.csv",'r')
fobj=csv.reader(csvfile)
name1=input("Enter name do you want to search")
for i in fobj:
if(i[0]==name1):
print(i)
30
def show_choices():
print('Menu')
print('1. Add Record')
print('2. Display Records')
print('3. Search a Record')
print('4. Exit')
def main():
while(True):
show_choices()
choice = input("Enter choice(1-4):")
print()
if choice == '1':
create()
elif choice == '2':
display()
elif choice == '3':
search()
elif choice == '4':
break
else:
print('Invalid input')
#call the main function.
main()
31
Output:
32
Q14: Write a python program to copy content from one file to another.
Source Code
f1=open("abc.txt","a+")
f1.write("Python is scripting language")
f1.write("\n")
f1.seek(0)
x=f1.read()
f2=open("xyz.txt","w+")
f2.write("Python is Object Oriented Language")
f2.write(x)
print(f2.tell())
print(f2.seek(0))
print(f2.read())
f1.close()
f2.close()
33
Output:
34
Q15: Write a python program to maintain book details like book code, book title
and price using stacks data structures? (implement push(), pop() and traverse()
functions).
Source Code:
book=[ ]
def push():
bcode=input("Enter bcode ")
btitle=input("Enter btitle ")
price=input("Enter price ")
bk=(bcode,btitle,price)
book.append(bk)
def pop():
if(book==[]):
print("Underflow / Book Stack in empty")
else:
bcode,btitle,price=book.pop()
print("poped element is ")
print("bcode ",bcode," btitle ",btitle," price ",price)
def traverse():
if not (book==[]):
n=len(book)
for i in range(n-1,-1,-1):
print(book[i])
else:
print("Empty , No book to display")
while True:
print("1. Push")
print("2. Pop")
print("3. Traversal")
print("4. Exit")
ch=int(input("Enter your choice "))
if(ch==1):
push()
elif(ch==2):
pop()
elif(ch==3):
traverse()
elif(ch==4):
print("End")
break
else:
print("Invalid choice")
35
Output:
36
Q16: Write a python program to maintain employee details like empno,name
and salary using Stack data structure? (implement insert(), delete() and
traverse() functions).
Source Code:
employee=[]
def push_element():
empno=input("Enter empno ")
name=input("Enter name ")
sal=input("Enter sal ")
emp=(empno,name,sal)
employee.append(emp)
def pop_element():
if(employee==[]):
print("Underflow / Employee Stack in empty")
else:
empno,name,sal=employee.pop(0)
print("poped element is ")
print("empno ",empno," name ",name," salary ",sal)
def traverse():
if not (employee==[]):
n=len(employee)
for i in range(n-1,-1,-1):
print(employee[i])
else:
print("Empty , No employee to display")
while True:
print("1. Add employee");
print("2. Delete employee");
print("3. Traversal")
print("4. Exit")
ch=int(input("Enter your choice "))
if(ch==1):
push_element()
elif(ch==2):
pop_element();
elif(ch==3):
traverse()
elif(ch==4):
print("End")
break
else:
print("Invalid choice")
37
Output:
38
Q17: Consider the following tables PRODUCT and CLIENT. Further answer the
questions given below.
Q.1. To display the details of those clients whose city is “delhi”
Q.2 To display the details of products whose price is in the range of 50
to 100
Q.3 To display client name ,city from table client and productname and
price from the table product with their corresponding matching p_id
Q.4 To increase the price of the product by 10
Q.5.To display city after removing duplicacy.
39
Source Code
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="Vijay@23",
database="test")
if mydb.is_connected():
print("Successfully connected")
cur=mydb.cursor()
p="create table PRODUCT1(P_Id varchar(5),Product_Name
varchar(20),Manufacturer varchar(10),Price float(5,2))"
#cur.execute(p)
p="insert into
PRODUCT1(P_Id,Product_Name,Manufacturer,Price)values(%s,%s,%s,%s)"
product=[('TP01','TELCOM Powder','LAK',40),('FW05','FACE
WASH','ABS',45),('BS01','BATH
SOAP','ABC',55),('SH06','SHAMPOO','XYZ',120),('FW12','FACE WASH','XYZ',95)]
#cur.executemany(p,product)
print("To display the details of products whose price is in the range of 50 to 100")
print("***************************************************************************")
query2="select * from PRODUCT1 where Price>=50 and Price<=100"
cur.execute(query2)
q2=cur.fetchall()
for row in q2:
print(row)
print("\n")
print("To increase the price of the product by 10")
print("******************************************")
query4="UPDATE PRODUCT1 SET Price=Price+10"
cur.execute(query4)
print(cur.rowcount,"records affected")
c="create table CLIENT1(C_Id integer(5),Client_Name varchar(20),City
varchar(10),P_Id varchar(5))"
#cur.execute(c)
c="insert into CLIENT1(C_Id,Client_Name,City,P_Id)values(%s,%s,%s,%s)"
client=[(1,'COSMETIC SHOP','Delhi','FW05'),(6,'TOTAL
HEALTH','Mumbai','BS01'),(12,'LIVE LIFE','Delhi','SH06'),(15,'PREETY
WOMAN','Delhi','FW12'),(16,'DREAMS','Banglore','TP01')]
#cur.executemany(c,client)
40
print("\n")
print("To display the details of those clients whose city is “delhi”")
print("*************************************************************")
query1="select * from CLIENT1 where City='Delhi'"
cur.execute(query1)
q1=cur.fetchall()
for row in q1:
print(row)
print("\n")
print("To display client name ,city from table client and productname and price
from the table product with their corresponding matching p_id")
print("*****************************************************************************
*********************************************************")
query3="select Client_Name,City,Product_Name,Price from client1, product1
where CLIENT1.P_Id=PRODUCT1.P_Id"
cur.execute(query3)
q3=cur.fetchall()
for row in q3:
print(row)
print("\n")
print("To display city after removing duplicacy")
print("****************************************")
query5="select distinct City from CLIENT1"
cur.execute(query5)
q5=cur.fetchall()
for row in q5:
print(row)
mydb.close()
41
Output :
42
Q 18: Consider the following tables CONSIGNOR and CONSIGNEE. Further
answer the questions given below.
Q1. To display the names of all the consignors from Mumbai
Q2. To display the cneeid, cnorname, cnoradress, cneenmae, cneeaddress for
every consignee.
Q3. To display consignee details in ascending order of cneename.
Q4. To display number of consignee from each city.
Q5. To display consigneecity after removing duplicacy.
43
Source Code
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="Vijay@23",
database="test")
if mydb.is_connected():
print("Successfully connected")
cur=mydb.cursor()
c1="create table CONSIGNOR(CNOR_Id varchar(5),CNOR_Name
varchar(20),CNOR_Address varchar(20),City varchar(10))"
#cur.execute(c1)
c1="insert into
CONSIGNOR(CNOR_Id,CNOR_Name,CNOR_Address,City)values(%s,%s,%s,%s)"
consignor=[('ND01','R SINGHAL','24;ABC ENCLAVE','NEW DELHI'),('ND02','AMIT
KUMAR','123;PALM AVENUE','NEW DELHI'),('MU15','R KOHLI','5/A;SOUTH
STREET','MUMBAI'),('MU50','S KAUR','27-K;WESTNED','MUMBAI')]
#cur.executemany(c1,consignor)
print("To display the names of all the consignors from Mumbai")
print("******************************************************")
query1="select CNOR_Name from CONSIGNOR where City='Mumbai'"
cur.execute(query1)
q1=cur.fetchall()
for row in q1:
print(row)
44
c2="create table CONSIGNEE(CNEE_Id varchar(5),CNOR_Id
varchar(5),CNEE_Name varchar(20),CNEE_Address varchar(20),CNEE_City
varchar(10))"
#cur.execute(c2)
c2="insert into
CONSIGNEE(CNEE_Id,CNOR_Id,CNEE_Name,CNEE_Address,CNEE_City)values(%s,
%s,%s,%s,%s)"
consignee=[('MU05','ND01','RAHUL KISHORE','5;PARK
AVENUE','MUMBAI'),('ND08','ND02','P DHINGRA','16/J;MOORE ENCLAVE','NEW
DELHI'),('KO19','MU15','A P ROY','2A;CENTRAL
AVENUE','KOLKATA'),('MU32','ND02','S MITTAL','P245;AB
COLONY','MUMBAI'),('ND48','MU50','B P JAIN','13;BLOCK D;A VIHAR','NEW DELHI')]
#cur.executemany(c2,consignee)
print("\n")
print("To display the cneeid, cnorname, cnoradress, cneenmae, cneeaddress for
every consignee")
print("*****************************************************************************
*********")
query2="Select CNEE_Id,CNOR_Address,CNEE_Name,CNEE_Address From
CONSIGNOR, CONSIGNEE Where CONSIGNOR.CNOR_Id = CONSIGNEE.CNOR_Id"
cur.execute(query2)
q2=cur.fetchall()
for row in q2:
print(row)
45
print("\n")
print("To display consignee details in ascending order of cneename")
print("************************************************************")
query3="select * from CONSIGNEE Order by CNEE_Name"
cur.execute(query3)
q3=cur.fetchall()
for row in q3:
print(row)
print("\n")
print("To display number of consignee from each city")
print("**********************************************")
query4="Select CNEE_City,count(CNEE_City) from CONSIGNEE group by
CNEE_City"
cur.execute(query4)
q4=cur.fetchall()
for row in q4:
print(row)
print("\n")
print("To display consigneecity after removing duplicacy")
print("**********************************************")
query5="select distinct CNEE_City from CONSIGNEE;"
cur.execute(query5)
q5=cur.fetchall()
for row in q5:
print(row)
mydb.close()
46
Output :
47
Q19: Consider the following tables VEHICLE and TRAVEL. Write SQL commands
for the queries (i) to (iv) and output for (v) & (viii) based on a given table.
Note:
PERKM is Travelling Charges per kilometer.
Km is kilometers Travelled
NOP is number of passangers travelled in vechicle.
Q1: To display CNO, CNAME, TRAVELDATE from the table TRAVEL in
descending order of CNO.
Q2: To display the CNAME of all customers from the table TRAVEL who are
travelling by vechicle with code V01 or V02.
Q3: To display the CNO and CNAME of those customers from the table TRAVEL
who travelled between ‘2015-12¬31’ and ‘2015-05-01’.
Q4: To display all the details from table TRAVEL for the customers, who have
travel distance more than 120 KM in ascending order of NOP.
Q5: Select count (*), VCODE from TRAVEL group by VCODE having
count (*)>1;
Q6: Select distinct VCODE from travel :
48
Q7:Select A.VCODE, CNAME, VEHICLETYPE from TRAVEL A, VEHICLE B where
A. VCODE = B. VCODE and KM < 90;
Q8: Select CNAME, KM*PERKM from TRAVEL A, VEHICLE B where A.VCODE =
B.VCODE and A. VCODE =‘V05’;
Source Code:
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="Vijay@23",
database="test")
if mydb.is_connected():
print("Successfully connected")
cur=mydb.cursor()
v="create table VEHICLE(V_Code varchar(5),Vehicle_Type varchar(20),Per_Km
integer(10))"
#cur.execute(v)
v="insert into VEHICLE(V_Code,Vehicle_Type,Per_Km)values(%s,%s,%s)"
vehicle=[('V01','VOLVO BUS',150),('V02','AC DELUX BUS',125),('V03','ORDINARY
BUS',80),('V05','SUV',30),('V04','CAR',18)]
#cur.executemany(v,vehicle)
t="create table TRAVEL(C_No integer(5),C_Name varchar(20),Travel_Date
date,Km integer(5),V_Code varchar(5),NOP integer(5))"
#cur.execute(t)
t="insert into TRAVEL(C_No,C_Name,Travel_Date,Km
,V_Code,NOP)values(%s,%s,%s,%s,%s,%s)"
travel=[(101,'K.Niwal','2015-12-13',200,'V01',32),(103,'Fredrick Sym','2016-03-
21',120,'V03',45),(105,'Hitesh Jain','2016-04-23',450,'V02',42),(102,'Ravi
Anish','2016-01-13',80,'V02',40),(107,'John Malina','2015-02-
10',65,'V04',2),(104,'Sahanubhuti','2016-01-28',90,'V05',4),(106,'Ramesh Jaya','2016
-04-06',100,'V01',25)]
#cur.executemany(t,travel)
print("\n")
print("To display CNO, CNAME, TRAVELDATE from the table TRAVEL in
descending order of CNO.")
print("*****************************************************************************
******")
query1="select C_No,C_Name,Travel_Date from TRAVEL order by C_No desc"
cur.execute(query1)
49
q1=cur.fetchall()
for row in q1:
print(row)
print("\n")
print("To display the CNAME of all customers from the table TRAVEL who are
travelling by vechicle with code V01 or V02.")
print("*****************************************************************************
***********************************")
query2="select C_Name from TRAVEL where V_Code='V01' or V_Code='V02'"
print("done")
cur.execute(query2)
q2=cur.fetchall()
for row in q2:
print(row)
print("\n")
print("To display the CNO and CNAME of those customers from the table
TRAVEL who travelled between ‘2015-12¬31’ and ‘2015-05-01’.")
print("*****************************************************************************
*********************************************")
query3="select C_No,C_Name from TRAVEL where Travel_Date>='2015-12¬31'
and Travel_Date<='2015-05-01'"
cur.execute(query3)
q3=cur.fetchall()
for row in q3:
print(row)
print("\n")
print("To display all the details from table TRAVEL for the customers, who have
travel distacne more than 120 KM in ascending order of NOP.")
print("*****************************************************************************
*******************************************************")
query4="select *from TRAVEL where Km>120 order by NOP"
cur.execute(query4)
q4=cur.fetchall()
for row in q4:
print(row)
print("\n")
print("OUTPUT-1.")
print("*********")
50
query5="select count(*), V_Code from TRAVEL group by V_Code having
count(*)>1"
cur.execute(query5)
q5=cur.fetchall()
for row in q5:
print(row)
print("\n")
print("OUTPUT-2.")
print("*********")
query6="select distinct V_Code from TRAVEL"
cur.execute(query6)
q6=cur.fetchall()
for row in q6:
print(row)
print("\n")
print("OUTPUT-3.")
print("*********")
query7="select A.V_Code, C_Name, Vehicle_Type from TRAVEL A, Vehicle B
where A.V_code = B.V_code and Km < 90"
cur.execute(query7)
q7=cur.fetchall()
for row in q7:
print(row)
print("\n")
print("OUTPUT-4.")
print("*********")
query8="select C_Name, Km*Per_Km from TRAVEL A, VEHICLE B where
A.V_Code = B.V_Code and A.V_Code='V05'"
cur.execute(query8)
q8=cur.fetchall()
for row in q8:
print(row)
mydb.close()
51
Q20: Write SQL commands for the queries (i) to (iv) and output for (v) & (viii)
based on a table COMPANY and CUSTOMER.
Q1: To display Product name with Price which are having price less than
30000.
Q2:To display the name of the companies in reverse alphabetical order.
Q3: To increase the prize by 1000 for those customer whose name starts with S?
Q4: To add one more column total price with decimal (10,2) to the table
customer.
Q5:Select count(*) , City from COMPANY group by City;
Q6:Select min(Price), max(Price) from CUSTOMER where Qty>10;
Q7:Select avg(Qty) from CUSTOMER where NAME like ‘%r%’;
Q8:Select Product_Name, City, Price from COMPANY , CUSTOMER where
COMPANY.C_Id=CUSTOMER_C_Id and Product_Name=’MOBILE’;
52
Source Code :
import mysql.connector
mydb=mysql.connector.connect(host="localhost",user="root",passwd="Vijay@23",
database="test")
if mydb.is_connected():
print("Successfully connected")
cur=mydb.cursor()
c1="create table COMPANY(C_Id integer(5),Name varchar(20),City
varchar(20),Product_Name varchar(20))"
#cur.execute(c1)
c1="insert into COMPANY(C_Id,Name,City,Product_Name)values(%s,%s,%s,%s)"
company=[(111,'SONY','DELHI','TV'),(222,'NOKIA','MUMBAI','MOBILE'),(333,'ONIDA',
'DELHI','TV'),(444,'SONY','MUMBAI','MOBILE'),(555,'BLACKBERRY','MADRAS','MOBI
LE'),(666,'DELL','DELHI','LAPTOP')]
#cur.executemany(c1,company)
print("\n")
print("To display the name of the companies in reverse alphabetical order")
print("******************************************************************")
query2="select Name from COMPANY order by Name desc"
cur.execute(query2)
q2=cur.fetchall()
for row in q2:
print(row)
c2="create table CUSTOMER(Cust_Id integer(5),Name varchar(20),Price
integer(15),Qty integer(5),C_Id integer(5))"
#cur.execute(c2)
c2="insert into CUSTOMER(Cust_Id,Name,Price,Qty,C_Id)values(%s,%s,%s,%s,%s)"
customer=[(101,'ROSHAN SHARMA',70000,20,222),(102,'DEEPEK
KUMAR',50000,10,666),(103,'MOHAN KUMAR',30000,5,111),(104,'SAHIL
BANSAL',35000,3,333),(105,'NEHA SONI',25000,7,444),(106,'SONAL
AGGARWAL',20000,5,333),(107,'ARUN SINGH',50000,15,666)]
#cur.executemany(c2,customer)
print("\n")
print("To display those Product name with Price which are having price less than
30000")
53
print("********************************************************************")
query1="select Product_name,Price from COMPANY,CUSTOMER where
COMPANY.C_Id=CUSTOMER.C_Id and Price<30000"
cur.execute(query1)
q1=cur.fetchall()
for row in q1:
print(row)
print("\n")
print("To increase the prize by 1000 for those customer whose name starts with
S")
print("**************************************************************************")
query3="update CUSTOMER set Price = Price + 1000 where Name like 's%'"
cur.execute(query3)
print(cur.rowcount,"records affected")
print("\n")
print("To add one more column totalprice with decimal(10,2) to the table
customer")
print("***************************************************************************")
query4="alter TABLE CUSTOMER add Total_Price decimal(10,2)"
cur.execute(query4)
describe="desc customer"
cur.execute(describe)
q4=cur.fetchall()
for row in q4:
print(row)
print("\n")
print("OUTPUT-1.")
print("*********")
query5="select count(*),City from COMPANY group by City"
cur.execute(query5)
q5=cur.fetchall()
for row in q5:
print(row)
print("\n")
print("OUTPUT-2.")
54
print("*********")
query6="select min(Price), max(Price) from CUSTOMER where Qty>10"
cur.execute(query6)
q6=cur.fetchall()
for row in q6:
print(row)
print("\n")
print("OUTPUT-3.")
print("*********")
query7="select avg(Qty) from CUSTOMER where Name like '%r%'"
cur.execute(query7)
q7=cur.fetchall()
for row in q7:
print(row)
print("\n")
print("OUTPUT-4.")
print("*********")
query8="select Product_Name, City, Price from COMPANY , CUSTOMER where
COMPANY.C_Id=CUSTOMER.C_Id and Product_Name='MOBILE'"
cur.execute(query8)
q8=cur.fetchall()
for row in q8:
print(row)
mydb.close()
55
Output:
56
57