Python Practical Record - Grade 12
Python Practical Record - Grade 12
Program:
import random
def gen():
gen()
Output:
Program:
def rand(n):
import random
start = 10**(n-1)
stop = 10**n
n = int(input("Enter a number:"))
rand(n)
rand(n)
Output:
3. Write a program to create a function that takes two numbers and
returns the number that has minimum one's digit.
Program:
def comp(n,n1):
a = n%10
b = n1%10
if a<b:
else:
n = int(input("Enter a number:"))
comp(n,n1)
Output:
Program:
d = (y-x)/3
print("The series is:",x,',', x+d,',', x+2*d,',', y)
func(x,y)
Output:
Output:
ch = ''
v=0
c=0
l=0
u=0
r = f.read()
for i in r:
if i in 'aeiouAEIOU':
v+=1
else:
c+=1
for i in r:
if i.isupper() == True:
u+=1
else:
l+=1
print('Vowels',v)
print('Consonants',c)
Output:
7. Write a program to remove all the lines that contain the character
letter 'a' in a file and write it to another file.
Program:
for i in f:
if 'a' not in i:
f1.write(i)
f.close()
f1.close()
Output:
8. Create a binary file with name and role number search for a given
role number and search for a given role number and display the name
and if not found display an appropriate message.
Program (i):
import pickle
def record():
f = open(r"C:/Users/user/Desktop/Bhavika
12A/Record/student.dat",'wb')
n = int(input("How many records?"))
d = {}
for i in range(n):
r = int(input("Enter roll number:"))
n = input("Enter name:")
d[r]=n
pickle.dump(d,f)
f.close()
record()
Program(ii):
import pickle
def search():
f = open(r"C:/Users/user/Desktop/Bhavika
12A/Record/student.dat",'rb')
n = int(input("Enter roll number:"))
c=0
try:
while True:
data = pickle.load(f)
for i in data:
if i == n:
print(i,data[i])
c+=1
except EOFError:
if c == 0:
print("Record not found")
else:
pass
f.close()
search()
Output:
9. Write a program to create a binary file with roll number, name and
marks. Input a roll number and update the marks.
Program:
import pickle
def write():
f = open(r'C:/Users/user/Desktop/Bhavika 12A/Record/test - rec
9.dat','wb')
n = int(input("How many records?"))
rec = []
for i in range(n):
r = int(input("Enter roll number:"))
n = input("Enter name:")
m = float(input("Enter marks:"))
data = [r,n,m]
rec.append(data)
pickle.dump(rec,f)
f.close()
def update():
f = open(r'C:/Users/user/Desktop/Bhavika 12A/Record/test - rec
9.dat','rb+')
f.seek(0)
found = 0
roll = int(input("Enter roll number to update:"))
t = pickle.load(f)
for i in t:
if i[0]==roll:
i[2]=float(input("Enter marks:"))
found = 1
f.seek(0)
pickle.dump(t,f)
if found == 0:
print("Not found")
f.close()
def read():
f = open(r"C:/Users/user/Desktop/Bhavika 12A/Record/test - rec
9.dat",'rb+')
rec = pickle.load(f)
for i in rec:
print(i)
f.close()
while True:
print('Menu','1.Write','2.Update','3.Read','4.Exit',sep='\n')
o = int(input("Enter number:"))
if o ==1:
write()
if o==2:
update()
elif o==3:
read()
elif o==4:
break
else:
print("Invalid option")
print("Thank you")
Output:
10.Create a csv file using userID and password, read and search the
password for given userID.
Program:
import csv
def write():
f = open("C:/Users/user/Desktop/Bhavika 12A/Record/csv file - rec
10.csv","w",newline='')
s = csv.writer(f)
s.writerow(['Username','Password'])
n = int(input("Enter number of records:"))
for i in range(n):
u = input("Enter username:")
p = input("Enter password:")
l = [u,p]
s.writerow(l)
f.close()
def read():
e = input("Enter username:")
f1 = open("C:/Users/user/Desktop/Bhavika 12A/Record/csv file - rec
10.csv","r")
r = csv.reader(f1)
for rec in r:
if rec[0]==e:
print("Password is:",rec[1])
f1.close()
write()
read()
Output:
11.Write a function that reads a csv file ad creates another csv file with
the same content but with a different delimiter.
Program:
def create()
import csv
f = open(r"C:/Users/user/Desktop/Bhavika 12A/Record/file -
rec11.csv",'r',newline='')
r = csv.reader(f)
f1 = open(r"C:/Users/user/Desktop/Bhavika 12A/Record/2nd file rec
11.csv",'w',newline='')
w = csv.writer(f1,delimiter = '|')
for i in r:
w.writerow(i)
f.close()
f1.close()
create()
Ouput:
12. Program to create a CSV file and store empno, name, salary and
search any empno and display name, salary and if not found print
appropriate message.
Program:
import csv
def record():
f = open(r'C:/Users/user/Desktop/Bhavika 12A/Record/record - rec
12.csv','w',newline='')
w = csv.writer(f)
w.writerow(['EmployeeNumber','Name','Salary'])
n = int(input("Enter number of records:"))
for i in range(n):
empno = input("Enter employee number:")
n = input("Enter name:")
s = float(input("Enter salary:"))
l = list([empno,n,s])
w.writerow(l)
f.close()
record()
def search():
import csv
f = open(r'C:/Users/user/Desktop/Bhavika 12A/Record/record - rec
12.csv','r',newline='')
e = input("Enter employee number to search:")
wr = csv.reader(f)
next(wr)
for i in wr:
if i[0]==e:
print(i[1])
print(i[2])
break
search()
Output:
13. Write functions:
i. To create a text file "text.txt" with few lines of text.
ii. To count the number of lines with 'B' in the file test.txt.
iii. To count the number of words starting with letter 'E' or 'O'.
Program:
def write():
f = open(r"C:/Users/user/Desktop/Bhavika
12A/Record/test(rec13).txt",'w')
t = "Bear and Goldilocks\nGoldilocks and the three bears\nElephant
and the ant\nLion and mouse"
f.write(t)
f.close()
write()
def B():
f = open(r"C:/Users/user/Desktop/Bhavika
12A/Record/test(rec13).txt",'r')
r = f.readlines()
b=0
for i in range(len(r)):
s = r[i].split()
if s[0][0]=='B':
b+=1
print("Number of lines starting with B:",b)
f.close()
B()
def EorG():
f = open(r"C:/Users/user/Desktop/Bhavika
12A/Record/test(rec13).txt",'r')
r = f.readlines()
e=0
for i in range(len(r)):
s = r[i].split()
for j in range(len(s)):
if s[j][0]=='E' or s[j][0]=='G':
e+=1
print("Number of words starting with E or G:",e)
f.close()
EorG()
Output:
14. Write a menu driven program to perform all the basic operations in
a binary file "TELEPHONE.DAT" which contains telephone number,
customer name and area.
i. Inserting records
ii. Reading all records and displaying
iii. Updating record based on given telephone number
iv. Searching record based on given telephone number
v. Deleting a record based on given customer name
Program:
import pickle
def choice():
print("Hello! Welcome to - Telephone menu -")
print("Choose:")
print("1.Inserting records")
print("2.Reading all records and displaying")
print("3.Updating record based on given telephone number")
print("4.Searching record based on given telephone number")
print("5.Deleting a record based on given customer name")
c = int(input("Enter number to perform task:"))
if c==1:
one()
elif c==2:
two()
elif c==3:
three()
elif c==4:
four()
elif c==5:
five()
else:
print("INVALID NUMBER ENTERED!")
def one():
f = open(r"C:/Users/user/Desktop/Bhavika
12A/Record/TELEPHONE.DAT",'wb')
n = int(input("Enter number of records:"))
rec = []
print()
for i in range(n):
n = input("Enter name of customer:")
t = int(input("Enter telephone number:"))
a = input("Enter area of customer:")
data = [n,t,a]
rec.append(data)
pickle.dump(rec,f)
f.close()
def two():
f = open(r"C:/Users/user/Desktop/Bhavika
12A/Record/TELEPHONE.DAT",'rb+')
rec = pickle.load(f)
print()
for i in rec:
print(i)
print()
f.close()
def three():
f = open(r'C:/Users/user/Desktop/Bhavika
12A/Record/TELEPHONE.DAT','rb+')
f.seek(0)
found = 0
n = int(input("Enter telephone number to update:"))
t = pickle.load(f)
for i in t:
if i[1]==n:
i[1]=int(input("Enter new telephone number:"))
found = 1
f.seek(0)
pickle.dump(t,f)
if found == 0:
print("Not found")
f.close()
print("NEW RECORD.....")
print()
d1 = two()
print()
def four():
import pickle
f = open(r"C:/Users/user/Desktop/Bhavika
12A/Record/TELEPHONE.DAT",'rb')
t = int(input("Enter telephone number:"))
c=0
try:
while True:
data = pickle.load(f)
for i in data:
if i[1] == t:
print("Record found....",i[0],i[1],i[2])
print()
c+=1
except EOFError:
if c == 0:
print("Record not found")
else:
pass
f.close()
def five():
import pickle
f = open(r"C:/Users/user/Desktop/Bhavika
12A/Record/TELEPHONE.DAT",'rb+')
n = input("Enter customer name:")
f.seek(0)
try:
l=[]
while True:
data = pickle.load(f)
if data[0]!=n:
l.append(data)
except EOFError:
f.seek(0)
for i in l:
pickle.dump(i,f)
print("Record deleted")
print("UPDATED RECORD....")
print()
d2 = two()
f.close()
def five():
import pickle
f = open(r"C:/Users/user/Desktop/Bhavika
12A/Record/TELEPHONE.DAT",'rb')
rec = pickle.load(f)
f.close()
n = input("Enter customer name to delete:")
l = []
for r in rec:
if r[0] != n:
l.append(r)
f = open(r"C:/Users/user/Desktop/Bhavika
12A/Record/TELEPHONE.DAT", 'wb')
pickle.dump(l, f)
f.close()
print("Record deleted")
print("UPDATED RECORD....")
print()
two()
def more():
while 'y':
i = input("Do you want to enter more?.....y/n....:")
if i == 'y' or i=='Y':
choice()
elif i == 'n':
print("THANK YOU! EXITING....")
break
choice()
more()
Output:
15. Write a python program to implement a stack using a list data
structures write functions:
a) to add an element
b) to delete an element
c) to display the stack
Program:
def isEmpty(stk):
if stk==[]:
return True
else:
return False
def Push(stk,item):
stk.append(item)
top=len(stk)-1
def Pop(stk):
if isEmpty(stk):
return "Underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item
def Peek(stk):
if isEmpty(stk):
return "Underflow"
else:
top=len(stk)-1
return stk[top]
def Display(stk):
if isEmpty(stk):
print("Stack empty")
else:
top=len(stk)-1
print(stk[top],"<-top")
for i in range(top-1,-1,-1):
print(stk[a])
stack=[]
top=None
while True:
print("Stack operations")
print("1.Push")
print("2.Pop")
print("3.Peek")
print("4.Display stack")
print("5.Exit")
ch=int(input("Enter your choice:"))
if ch==1:
item=int(input("Enter item"))
Push(stack,item)
elif ch==2:
item=Pop(stack)
if item=="Underflow":
print("Underflow! Stack is empty")
else:
print("Popped item is",item)
elif ch==3:
item=Peek(stack)
if item=="Underflow":
print("Underflow! Stack is empty!")
else:
print("Topmost item is",item)
elif ch==4:
Display(stack)
elif ch==5:
break
else:
print("Invalid choice!")
Output:
STACK OPERATIONS:
1.Push
2.Pop
3.Display stack
4.Peek
5.Exit
Enter your choice:1
Enter item:8
STACK OPERATIONS:
1.Push
2.Pop
3.Display stack
4.Peek
5.Exit
Enter your choice:2
Popped item is 8
STACK OPERATIONS:
1.Push
2.Pop
3.Display stack
4.Peek
5.Exit
Enter your choice:3
Stack Empty
STACK OPERATIONS:
1.Push
2.Pop
3.Display stack
4.Peek
5.Exit
STACK OPERATIONS:
1.Push
2.Pop
3.Display stack
4.Peek
5.Exit
Enter your choice:4
Underflow! Stack is EMPTY
STACK OPERATIONS:
1.Push
2.Pop
3.Display stack
4.Peek
5.Exit
Enter your choice:5
16. Write a python program to implement a stack:
Each element of a stack TICKET(a list) is a dictionary with keys
'TICKETNO', and 'PNAME'. The values for 'TICKETNO' and 'PNAME' are
of type integers and string respectively.
Write functions:
- PUSH(TICKET) to push an element into the stack. The details of the
ticket to be pushed are to be input from the user.
- POP(TICKET) to pop an element from the stack. The popped element
should be returned by the function. If the stack is empty, function
should return None.
print('%10s'%'Empno','%10s'%'Name','%10s'%'Department','%10s'%'Sala
ry')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'%10s'%r[3])
choice=None
while True:
print('1.Add Record')
print('2.Display Record')
print('0.Exit')
choice=int(input("Enter choice:"))
if choice==1:
sqlinsert()
continue
elif choice==2:
sqldisplay()
continue
elif choice==0:
con.close()
print("Bye! Thank you!")
break
else:
print("INVALID CHOICE!!!")
continue
Output:
18. Program to connect with database and search employee number in
table employee and display record, if empno not found appropriate
message.
Program:
import mysql.connector as mycon
con=mycon.connect(host='localhost',user='root',password='mysql')
ur=con.cursor()
ur.execute("create database if not exists company2")
ur.execute("use company2")
ur.execute("create table if not exists employee(empno int,name
varchar(20),dept varchar(20),salary int)")
con.commit()
def sqlinsert():
e=int(input("Enter employee number:"))
n=input("Enter name:")
d=input("Enter department:")
s=int(input("Enter salary:"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
ur.execute(query)
con.commit()
print('DATA SAVED!')
def sqldisplay():
query='select*from employee order by salary desc'
ur.execute(query)
result=ur.fetchall()
print('%10s'%'Empno','%10s'%'Name','%10s'%'Department','%10s'%'Sala
ry')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'%10s'%r[3])
def sqlsearch():
eno = int(input("Enter employee number to search:"))
q = "select * from employee where empno={}".format(eno)
ur.execute(q)
result = ur.fetchall()
if ur.rowcount == 0:
print("Employee not found!")
else:
print('%10s'%'Empno','%10s'%'Name','%10s'%'Department','%10s'%'Sala
ry')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'%10s'%r[3])
choice=None
while True:
print('1.Add Record')
print('2.Display Record')
print('3.Search Record')
print('0.Exit')
choice=int(input("Enter choice:"))
if choice==1:
sqlinsert()
continue
elif choice==2:
sqldisplay()
continue
elif choice==3:
sqlsearch()
continue
elif choice==0:
con.close()
print("Bye! Thank you!")
break
else:
print("INVALID CHOICE!!!")
continue
Output:
19. Program to connect with database and update the employee record
of entered empno.
Program:
import mysql.connector as mycon
con=mycon.connect(host='localhost',user='root',password='mysql')
ur=con.cursor()
ur.execute("create database if not exists company2")
ur.execute("use company2")
ur.execute("create table if not exists employee(Empno int,Name
varchar(20),Dept varchar(20),Salary int)")
con.commit()
def sqlinsert():
e=int(input("Enter employee number:"))
n=input("Enter name:")
d=input("Enter department:")
s=int(input("Enter salary:"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
ur.execute(query)
con.commit()
print('DATA SAVED!')
def sqldisplay():
query='select*from employee order by salary desc'
ur.execute(query)
result=ur.fetchall()
print('%10s'%'Empno','%10s'%'Name','%10s'%'Department','%10s'%'Sala
ry')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'%10s'%r[3])
def sqlsearch():
eno = int(input("Enter employee number to search:"))
q = "select * from employee where empno={}".format(eno)
ur.execute(q)
result = ur.fetchall()
if ur.rowcount == 0:
print("Employee not found!")
else:
print('%10s'%'Empno','%10s'%'Name','%10s'%'Department','%10s'%'Sala
ry')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'%10s'%r[3])
def sqlupdate():
ans = "y"
while ans.lower()=='y':
eno = int(input("Enter empno to update:"))
q = "select * from employee where empno={}".format(eno)
ur.execute(q)
result = ur.fetchall()
if ur.rowcount==0:
print("Sorry not found")
else:
print('%10s'%'Empno','%10s'%'Name','%10s'%'Department','%10s'%'Sala
ry')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'%10s'%r[3])
ans = input("Do you want to continue? (y/n):")
if ans.lower()=='y':
d = input("Enter new department:")
s = int(input("Enter new salary:"))
else:
break
q = "update employee set Dept='{}', Salary={} where
empno={}".format(d,s,eno)
ur.execute(q)
con.commit()
print("Record Updates!")
ans = input("Do you want to update more? (y/n):")
choice=None
while True:
print('1.Add Record')
print('2.Display Record')
print('3.Search Record')
print('4.Update Record')
print('0.Exit')
choice=int(input("Enter choice:"))
if choice==1:
sqlinsert()
continue
elif choice==2:
sqldisplay()
continue
elif choice==3:
sqlsearch()
continue
elif choice == 4:
sqlupdate()
continue
elif choice==0:
con.close()
print("Bye! Thank you!")
break
else:
print("INVALID CHOICE!!!")
continue
Output:
20. Program to connect with database and to delete the record of
entered employee number.
Program:
import mysql.connector as mycon
con=mycon.connect(host='localhost',user='root',password='mysql')
ur=con.cursor()
ur.execute("create database if not exists company2")
ur.execute("use company2")
ur.execute("create table if not exists employee(Empno int,Name
varchar(20),Dept varchar(20),Salary int)")
con.commit()
def sqlinsert():
e=int(input("Enter employee number:"))
n=input("Enter name:")
d=input("Enter department:")
s=int(input("Enter salary:"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
ur.execute(query)
con.commit()
print('DATA SAVED!')
def sqldisplay():
query='select*from employee order by salary desc'
ur.execute(query)
result=ur.fetchall()
print('%10s'%'Empno','%10s'%'Name','%10s'%'Department','%10s'%'Sala
ry')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'%10s'%r[3])
def sqlsearch():
eno = int(input("Enter employee number to search:"))
q = "select * from employee where empno={}".format(eno)
ur.execute(q)
result = ur.fetchall()
if ur.rowcount == 0:
print("Employee not found!")
else:
print('%10s'%'Empno','%10s'%'Name','%10s'%'Department','%10s'%'Sala
ry')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'%10s'%r[3])
def sqlupdate():
ans = "y"
while ans.lower()=='y':
eno = int(input("Enter empno to update:"))
q = "select * from employee where empno={}".format(eno)
ur.execute(q)
result = ur.fetchall()
if ur.rowcount==0:
print("Sorry not found")
else:
print('%10s'%'Empno','%10s'%'Name','%10s'%'Department','%10s'%'Sala
ry')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'%10s'%r[3])
ans = input("Do you want to continue? (y/n):")
if ans.lower()=='y':
d = input("Enter new department:")
s = int(input("Enter new salary:"))
else:
break
q = "update employee set Dept='{}', Salary={} where
empno={}".format(d,s,eno)
ur.execute(q)
con.commit()
print("Record Updates!")
ans = input("Do you want to update more? (y/n):")
def sqldelete():
ans='y'
while ans.lower()=='y':
eno = int(input("Enter empno to delete:"))
q = 'select * from employee where empno={}'.format(eno)
ur.execute(q)
result = ur.fetchall()
if ur.rowcount==0:
print("Sorry! Not found")
else:
print('%10s'%'Empno','%10s'%'Name','%10s'%'Department','%10s'%'Sala
ry')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'%10s'%r[3])
ans = input("Do you want to continue? (y/n):")
if ans.lower()=='y':
q = 'delete from employee where empno={}'.format(eno)
ur.execute(q)
con.commit()
print("Record Deleted!")
else:
break
ans = input("Do you want to delete more? (y/n):")
choice=None
while True:
print('1.Add Record')
print('2.Display Record')
print('3.Search Record')
print('4.Update Record')
print('5.Delete Record')
print('0.Exit')
choice=int(input("Enter choice:"))
if choice==1:
sqlinsert()
continue
elif choice==2:
sqldisplay()
continue
elif choice==3:
sqlsearch()
continue
elif choice == 4:
sqlupdate()
continue
elif choice == 5:
sqldelete()
continue
elif choice==0:
con.close()
print("Bye! Thank you!")
break
else:
print("INVALID CHOICE!!!")
continue
Output:
TABLE: FLIGHTS
Output:
mysql> create table Flights(FL_NO char(10) primary key, DEPARTURE varchar(20) NOT
NULL, ARRIVAL varchar(20), NO_FLIGHTS INT NOT NULL,NO_OF_STOPS INT);
Query OK, 0 rows affected (0.31 sec)
mysql> desc flights;
+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| FL_NO | char(10) | NO | PRI | NULL | |
| DEPARTURE | varchar(20) | NO | | NULL | |
| ARRIVAL | varchar(20) | YES | | NULL | |
| NO_FLIGHTS | int | NO | | NULL | |
| NO_OF_STOPS | int | YES | | NULL | |
+-------------+-------------+------+-----+---------+-------+
5 rows in set (0.06 sec)
TABLE: FARE
Output:
mysql> create table FARE(FL_NO CHAR(10) primary key, AIRLINES varchar(20) not null,
FARE DECIMAL(10,2) NOT NULL, TAX DECIMAL(10,2) NOT NULL);
Query OK, 0 rows affected (0.66 sec)
TABLE : FLIGHT
FL_NO DEPARTURE ARRIVAL NO FLIGHTS NO STOPS
IC301 MUMBAI DELHI 8 0
IC799 BALNGALORE DELHI 2 1
MC101 INDORE MUMBAI 3 0
IC302 DELHI MUMBAI 8 0
AM812 KANPUR BANGLORE 3 1
IC899 MUMBAI KOCHI 1 4
AM501 DELHI TRIVANDRUM 1 5
MU499 MUMBAI MADRAS 3 3
IC701 DELHI AHMEDABAD 4 0
Output:
mysql> insert into Flight values("IC301","MUMBAI","DELHI",8,0),
(“IC799”,”BANGALORE”,”DELHI”,2,1),("MC101","INDORE","MUMBAI",3,0),
("IC302","DELHI","MUMBAI",8,0),("AM812","KANPUR","BANGALORE",3,1),
("IC899","MUMBAI","KOCHI",1,4),("AM501","DELHI","TRIVANDRUM",1,5),
("MU499","MUMBAI","MADRAS",3,3),("IC701","DELHI","AHMEDABAD",4,0);
Query OK, 7 rows affected (0.08 sec)
Records: 7 Duplicates: 0 Warnings: 0
TABLE : FARE
Output:
mysql> create table FARE1(FL_NO varchar(20) primary key,AIRLINES varchar(20),FARE int ,
TAX int);
Query OK, 0 rows affected (0.52 sec)
2. Write SQL commands for the following questions based on the above tables:
i) Display Flight_No, No of flights arriving to Delhi .
Output:
mysql> select FL_NO, NO_FLIGHTS from flight where ARRIVAL = "Delhi";
+-------+------------+
| FL_NO | NO_FLIGHTS |
+-------+------------+
| IC301 | 8|
| IC799 | 2|
+-------+------------+
2 rows in set (0.00 sec)
ii) Display all the airlines that have maximum number of flights.
(iv) To display departure and arrival points of flights no IC302 and MU499.
mysql> select DEPARTURE, ARRIVAL from FLIGHT where FL_NO = "IC302" or FL_NO =
'MU499';
+-----------+---------+
| DEPARTURE | ARRIVAL |
+-----------+---------+
| DELHI | MUMBAI |
| MUMBAI | MADRAS |
+-----------+---------+
2 rows in set (0.00 sec)
mysql> select FL_NO, AIRLINES, max(FARE), min(FARE) from fare1 group by AIRLINES;
+-------+-----------------+-----------+-----------+
| FL_NO | AIRLINES | max(FARE) | min(FARE) |
+-------+-----------------+-----------+-----------+
| AM501 | JET AIRWAYS | 13450 | 13450 |
| IC302 | INDIAN AIRLINES | 8100 | 1050 |
| MC101 | DECCAN ARILINES | 3500 | 3500 |
| MU499 | SAHARA | 9400 | 9400 |
+-------+-----------------+-----------+-----------+
4 rows in set (0.01 sec)
(viii) Create a report which contains FL_NO, AIRLINES, TOTAL FARE of all airlines. Total
fare is calculated as fare+(fare*tax%*0.01).
(ix) Display the details of airlines whose name start with ‘IC’.
(x) Create a view which contains details of airlines which are arriving in Mumbai.
mysql>
mysql> select * from fare1;
+-------+-----------------+-------+------+
| FL_NO | FLIGHT_NAME | FARE | TAX |
+-------+-----------------+-------+------+
| AM501 | JET AIRWAYS | 13450 | 8 |
| IC302 | INDIAN AIRLINES | 4300 | 9 |
| IC701 | INDIAN AIRLINES | 6500 | 10 |
| IC799 | INDIAN AIRLINES | 1050 | 10 |
| IC899 | INDIAN AIRLINES | 8100 | 4 |
| MC101 | DECCAN ARILINES | 3500 | 4 |
| MU499 | SAHARA | 9600 | 5 |
+-------+-----------------+-------+------+
7 rows in set (0.02 sec)
(OR)
Alter table fare rename column airlines to flight_name;
TABLE : SCHOOL
Column name Data type Size Constraints
Code Integer Primary key
Teacher_name Varchar 20 Not null
Subject Char 20 Not null
DOJ Cate Not null
Periods Integer
Experience Integer
Output:
mysql> create table SCHOOL(Code int primary key, Teacher_name varchar(20) not null, Subject
char(20) not null, DOJ date not null, Periods int, Experience int);
Query OK, 0 rows affected (0.24 sec)
Table: ADMIN
Output:
mysql> create table ADMIN(code int primary key, gender varchar(20) not null, designation
char(20) not null);
Query OK, 0 rows affected (0.25 sec)
TABLE: SCHOOL
Output:
mysql> insert into school values(1001, "Ravi Shankar", "English", "2001/12/03", 24, 10),(1009,
"Priya Raj", "Physics", "1998/09/12", 26, 12), (1203, "Lasa Anand", "English", "2000/08/24",
24,15), (1045, "Yasraj", "Math", "2000/08/24", 24, 15), (1123,"Gagan","Physics", "1999/07/16",
28, 3), (1167, "Umesh","Chemistry","1998/05/11",22,5);
Query OK, 6 rows affected (0.08 sec)
TABLE: ADMIN
Code Gender Designation
1001 Male Vice principal
1203 Female Coordinator
1009 Female Coordinator
1045 Male HOD
1123 Male Senior teacher
1167 Male Senior teacher
Ouput:
mysql> insert into admin values(1001, "Male" , "Vice Principal"), (1203, "Female",
"Coordinator"), (1009, "Female","Coordinator"), (1045, "Male", "HOD"), (1123, "Male
", "Senior Teacher"), (1167, "Male", 'Senior Teacher');
Query OK, 6 rows affected (0.08 sec)
Records: 6 Duplicates: 0 Warnings: 0
5. (i) Display teacher name, periods of all teachers whose periods are less than 25 ans name
starts with either R or U
mysql> select Teacher_name, Periods from school where Periods<=25 and (Teacher_name like "R
%" or Teacher_name like "U%");
+--------------+---------+
| Teacher_name | Periods |
+--------------+---------+
| Ravi Shankar | 24 |
| Umesh | 22 |
+--------------+---------+
2 rows in set (0.00 sec)
(ii) Display the contents of school table in descending order of teacher name
(iv) Display teachername, code and designation from tables school and admin for female
teacher
mysql> select teacher_name from school where periods = (select min(periods) from school);
+--------------+
| teacher_name |
+--------------+
| Umesh |
+--------------+
1 row in set (0.04 sec)
mysql> update school, admin set Experience = Experience+2 where gender = "Female" and
admin.code = school.code;
Query OK, 2 rows affected (0.06 sec)
Rows matched: 2 Changed: 2 Warnings: 0
mysql> select * from school;
+------+--------------+-----------+------------+---------+------------+
| Code | Teacher_name | Subject | DOJ | Periods | Experience |
+------+--------------+-----------+------------+---------+------------+
| 1001 | Ravi Shankar | English | 2001-12-03 | 24 | 10 |
| 1009 | Priya Raj | Physics | 1998-09-12 | 26 | 14 |
| 1045 | Yasraj | Math | 2000-08-24 | 24 | 15 |
| 1123 | Gagan | Physics | 1999-07-16 | 28 | 3|
| 1167 | Umesh | Chemistry | 1998-05-11 | 22 | 5|
| 1203 | Lasa Anand | English | 2000-08-24 | 24 | 17 |
+------+--------------+-----------+------------+---------+------------+
6 rows in set (0.00 sec)
(x) Display code, teacher_name, salary to be paid where salary to be paid = period*507.50
(xi) Display code.teachername and subject of all teachers who have joined the school after
01/01/1999
mysql> select Teacher_name, Designation from school, admin where school.code = admin.code
and gender = "Male";
+--------------+----------------+
| Teacher_name | Designation |
+--------------+----------------+
| Ravi Shankar | Vice Principal |
| Yasraj | HOD |
| Gagan | Senior Teacher |
| Umesh | Senior Teacher |
+--------------+----------------+
4 rows in set (0.00 sec)
TABLE CLUB:
COLUMN NAME DATA TYPE SIZE CONSTRAINTS
COACH ID INTEGER 4 PRIMARY KEY
COACH NAME VARCHAR 20 NOT NULL
AGE INTEGER 2 >=18
SPORTS VARCHAR 20
DATE OF APP DATE
PAY DECIMAL 8,3
GENDER CHAR 2
Output:
mysql> create table CLUB(Coach_ID integer(4) primary key, Coach_name varchar(20) not null,
Age integer(2) check(Age>=18), Sports varchar(20), Date_of_app date, Pay float(8,3), Gender
char(2));
Query OK, 0 rows affected, 3 warnings (0.45 sec)
mysql> desc CLUB;
+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| Coach_ID | int | NO | PRI | NULL | |
| Coach_name | varchar(20) | NO | | NULL | |
| Age | int | YES | | NULL | |
| Sports | varchar(20) | YES | | NULL | |
| Date_of_app | date | YES | | NULL | |
| Pay | float(8,3) | YES | | NULL | |
| Gender | char(2) | YES | | NULL | |
+-------------+-------------+------+-----+---------+-------+
7 rows in set (0.05 sec)
Output:
mysql> insert into CLUB values(1,"Kukreja",35,"Karate","1996/03/27",1000,"M"),
(2,"Ravina",34,"Karate","1998/01/20",1200,"F"),(3, "Karan", 34,"Squash",
"1998/02/19",2000,"M"),(4, "Tarun", 33, "Basketball", "1998/01/01", 1500, "M"), (5, "Zubin", 36,
"Swimming", "1998/01/12", 750, "M"), (6, "Ketaki", 3
6, "Swimming", "1998/02/24", 800, "F"), (7, "Amkita", 39, "Squash", "1998/02/20", 2200, "F"),
(8, "Zareen", 37, "Karate", "1998/02/22", 1100, "F"), (9, "Kush", 41, "Swimming", "1998/01/13",
900, "M"), (10, "Sailya", 37, "Basketball", "1998/02/19", 3700, "M");
Query OK, 10 rows affected (0.05 sec)
Records: 10 Duplicates: 0 Warnings: 0
+----------+------------+------+------------+-------------+----------+--------+
| Coach_ID | Coach_name | Age | Sports | Date_of_app | Pay | Gender |
+----------+------------+------+------------+-------------+----------+--------+
| 1 | Kukreja | 35 | Karate | 1996-03-27 | 1000.000 | M |
| 2 | Ravina | 34 | Karate | 1998-01-20 | 1200.000 | F |
| 3 | Karan | 34 | Squash | 1998-02-19 | 2000.000 | M |
| 4 | Tarun | 33 | Basketball | 1998-01-01 | 1500.000 | M |
| 5 | Zubin | 36 | Swimming | 1998-01-12 | 750.000 | M |
| 6 | Ketaki | 36 | Swimming | 1998-02-24 | 800.000 | F |
| 7 | Amkita | 39 | Squash | 1998-02-20 | 2200.000 | F |
| 8 | Zareen | 37 | Karate | 1998-02-22 | 1100.000 | F |
| 9 | Kush | 41 | Swimming | 1998-01-13 | 900.000 | M |
| 10 | Sailya | 37 | Basketball | 1998-02-19 | 3700.000 | M |
+----------+------------+------+------------+-------------+----------+--------+
10 rows in set (0.00 sec)
(iv) To show all information about the swimming coaches in the club
(v) To list the name of all coaches with their date of appointment in descending order.
(vi) To display a report showing Coach_name, Pay, Age and Bonus(15% of Pay) for all
coaches.
(viii) Display all female coaches belonging to various sports except Karate.
mysql> select Coach_name from club where Gender = "F" and Sports!="Karate";
+------------+
| Coach_name |
+------------+
| Ketaki |
| Amkita |
+------------+
2 rows in set (0.00 sec)
(ix) Display name of all coaches whose name ends with ‘N’.
9. Create the table Mobile Master and Mobile Stock of the following structure:
Output:
Output:
mysql> create table mobilestock(S_ID varchar(10) Primary key, M_ID varchar(10), M_Qty
float(8,3), M_Supplier varchar(20));
Query OK, 0 rows affected, 1 warning (0.43 sec)
mysql> desc mobilestock;
+------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| S_ID | varchar(10) | NO | PRI | NULL | |
| M_ID | varchar(10) | YES | | NULL | |
| M_Qty | float(8,3) | YES | | NULL | |
| M_Supplier | varchar(20) | YES | | NULL | |
+------------+-------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
9. Write SQL commands for the following questions based on the above tables
(i)Display the Mobile Company, Mobile name and price in descending order of their
manufacturig date.
mysql> select M_company, M_name, M_price from mobilemaster order by M_Mf_Date desc;
+-----------+----------+----------+
| M_company | M_name | M_price |
+-----------+----------+----------+
| Sony | XperiaM | 7500.000 |
| Micromax | Unite3 | 4500.000 |
| Samsung | Galaxy | 4500.000 |
| Nokia | N100 | 2250.000 |
| Oppo | SelfieEx | 8500.000 |
+-----------+----------+----------+
5 rows in set (0.00 sec)
(ii) List the details of mobile whose name starts with “S”
(iii) Display the mobile supplier and quantity of all mobiles except “MB003”
(iv) To display the name of the mobile company price between 3000 and 5000.
mysql> select M_company from MOBILEMASTER WHERE M_price > 3000 and
M_price<5000;
+-----------+
| M_company |
+-----------+
| Samsung |
| Micromax |
+-----------+
2 rows in set (0.00 sec)
10. Create the tables TRAINER and COURSE of the following structure:
TABLE: TRAINER
TID TNAME CITY HIREDATE SALARY
101 Sunaina Mumbai 1998-10-15 90000
102 Anamika Delhi 1994-12-24 80000
103 Deepti Chandigarh 2001-12-21 82000
104 Meenakshi Delhi 2002-12-25 78000
105 Richa Mumbai 1996-01-12 95000
106 Maniprabha Chennai 2001-12-12 69000
Output:
mysql> create table TRAINER(TID integer(3) primary key, TNAME varchar(10), CITY
varchar(10), HIREDATE date, Salary float(8,3));
Query OK, 0 rows affected, 2 warnings (0.36 sec)
+----------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| TID | int | NO | PRI | NULL | |
| TNAME | varchar(10) | YES | | NULL | |
| CITY | varchar(10) | YES | | NULL | |
| HIREDATE | date | YES | | NULL | |
| SALARY | float(8,3) | YES | | NULL | |
+----------+-------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
TABLE COURSE
Output:
mysql> create table COURSE(CID varchar(10) Primary key, CNAME varchar(20), FEES int,
STARTDATE date, TID int);
Query OK, 0 rows affected (0.81 sec)
mysql> insert into course values("C201", "AGDCA", 120000, "2018/07/02", 101), ("C202",
"ADCA", 15000, "2018/07/15", 102), ("C203", "DCA", 10000, "2018/10/01", 103), ("C204",
"DDTP", 9000, "2018/09/15", 104), ("C205", "DHN", 20000, "2018/08/01", 105), ("C206", "O
LEVEL", 18000, "2018/07/25", 106);
Query OK, 6 rows affected (0.10 sec)
Records: 6 Duplicates: 0 Warnings: 0
+------+---------+-------+------------+------+
| CID | CNAME | FEES | STARTDATE | TID |
+------+---------+-------+------------+------+
| C201 | AGDCA | 12000 | 2018-07-02 | 101 |
| C202 | ADCA | 15000 | 2018-07-15 | 102 |
| C203 | DCA | 10000 | 2018-10-01 | 103 |
| C204 | DDTP | 9000 | 2018-09-15 | 104 |
| C205 | DHN | 20000 | 2018-08-01 | 105 |
| C206 | O LEVEL | 18000 | 2018-07-25 | 106 |
+------+---------+-------+------------+------+
6 rows in set (0.00 sec)
11. Write SQL commands for the following questions based on the above tables
(i) Display the trainer name, city and salary in descending order of their hire.
mysql> select TNAME, CITY, SALARY from TRAINER order by HIREDATE desc;
+------------+------------+-----------+
| TNAME | CITY | SALARY |
+------------+------------+-----------+
| Meenakshi | Delhi | 78000.000 |
| Deepti | Chandigarh | 82000.000 |
| Maniprabha | Chennai | 69000.000 |
| Sunaina | Mumbai | 90000.000 |
| Richa | Mumbai | 95000.000 |
| Anamika | Delhi | 80000.000 |
+------------+------------+-----------+
6 rows in set (0.00 sec)
(ii) To display the TNAME and CITY of trainer who joined the institute in the month of
December 2001.
mysql> select TNAME, CITY from trainer where hiredate between "2001/12/01" and
"2001/12/31";
+------------+------------+
| TNAME | CITY |
+------------+------------+
| Deepti | Chandigarh |
| Maniprabha | Chennai |
+------------+------------+
2 rows in set (0.00 sec)
(iii) To display TNAME, HIREDATE , CNAME , STARTDATE from tables TRAINER and
COURSE of all those courses whose FEES is less than or equal to 10000.