sc
sc
PROGRAMS
1.Write a program to create a random number generator
that generates a number between 1 and 6 (simulates a
dice):
Concept used:
import, random module, function, return
Source Code:
import random
def func():
a=random.randint(1,6)
return a
print('Number is: ',func())
OUTPUT:
Number is: 4
1
2.Write a program to create a function that takes a
number n and then returns a randomly generated number
having exactly n digits.
Concepts used:
import, random module, function, print()
Source Code:
import random
def func1(n):
start=10**(n-1)
stop=10**n
a=random.randrange(start,stop)
print("Random number generated is:",a)
func1(int(input("Enter number of digits: ")))
OUTPUT:
Enter number of digits: 4
Random number generated is: 4709
2
3.Write a program to create a function that takes two
numbers and returns the number that has minimum ones
digit.
Concepts used:
function, if and else, print()
Source Code:
def func(a,b):
a1=a%10
b1=b%10
if a1<b1:
return a
else:
return b
OUTPUT:
Enter first number: 12
Enter second number: 34
The number with minimum ones digit is: 12
3
4.Write a program that generates a series using a
function which takes first and last values of the
series and then generates 4 terms that are equidistant.
Concepts used:
function, return, print()
Source Code:
def func(a,b):
s=(b-a)
i=(s/3)
w,x,y,z=a,a+i,a+(2*i),(a+3*i)
return w,x,y,z
OUTPUT:
Enter first number: 1
Enter last number: 7
The series is: (1, 3.0, 5.0, 7.0)
4
5. Write a program to read a text file line by line and
display each word separated by a hash(#).
Concepts used:
open(), readlines(), for loop, print(), close()
Source Code:
f=open("prac1.txt",'r')
l=''
re=f.readlines()
for i in re:
a=i.split()
for j in a:
l+=j
l+='#'
print(l[:-1])
f.close()
OUTPUT:
computer#science#is#really#fun
5
6.Write a program to read a text file and display the
number of vowels/consonants/uppercase/lowercase
characters in the file.
Concepts used:
open(), readlines(), for loop, if and else, print(),
close()
Source Code:
f=open("prac2.txt",'r')
vow='aeiouAEIOU'
v=0
c=0
up=0
low=0
re=f.readlines()
for i in re:
b=i.split()
for j in b:
for z in j:
if z in vow:
v+=1
else:
c+=1
if z.isupper():
up+=1
else:
low+=1
print('vowels:',v)
print('consonants:',c)
print('uppercase:',up)
print('loweercase:',low)
f.close()
6
#Sample Data
OUTPUT:
vowels: 25
consonants: 35
uppercase: 0
lowercase: 60
7
7.Write a program to remove all the lines that contain
the character (‘a’) in a file and write it to another
file.
Concepts used:
open(), readlines(), for loop, if and else, print(),
close()
Source Code:
f=open('prac7.txt','r')
f1=open('prac7a.txt','w')
a=f.readlines()
for i in a:
if 'a' not in i:
f1.write(i)
f1=open('prac7a.txt','r')
print(f1.read())
f.close()
f1.close()
8
8.Create a binary file with name and roll number.
Search for a given roll number and display the name and
if not found, display appropriate message
Concepts used:
import, pickle module, dump(), load(), open(), for
loop, try and except, while loop, if and else, print(),
break
Source Code:
import pickle
f=open('prac8.dat','wb')
f=open('prac8.dat','rb')
r_inp=int(input("Enter roll no. to search: "))
try:
while True:
data=pickle.load(f)
if data[0]==r_inp:
print(data)
break
except EOFError:
print("No such record found")
OUTPUT:
No. of records: 3
Roll No.: 1
Name: Riya
Roll No.: 2
Name: Rahul
9
Roll No.: 3
Name: Thomas
Enter roll no. to search: 3
[3, 'Thomas']
9) Write a program to create a binary file with roll
number, name and marks. Input a roll no. and update the
marks.
Concepts used:
import, pickle module, dump(), load(), seek(), open(),
for loop, try and except, while loop, if and else,
print(), break
Source Code:
import pickle
f=open('prac9.dat','wb')
rec=[]
while True:
rno=int(input("Roll No.: "))
name=input("Name: ")
mar=int(input("Marks: "))
data=[rno,name,mar]
rec.append(data)
f=open('prac9.dat','rb+')
f.seek(0)
found=0
10
f.seek(0)
pickle.dump(t,f)
if found==0:
print("Not found")
f.seek(0)
try:
while True:
data=pickle.load(f)
print(data)
break
except EOFError:
print("No such record found")
f.close()
OUTPUT:
Roll No.: 1
Name: Aarav
Marks: 25
Do you want to continue y/n: y
Roll No.: 2
Name: Ria
Marks: 89
Do you want to continue y/n: y
Roll No.: 3
Name: Thomas
Marks: 99
Do you want to continue y/n: n
Enter roll no. to update: 3
Enter new marks: 100
[[1, 'Aarav', 25], [2, 'Ria', 89], [3, 'Thomas', '100']]
11
10.Create a CSV file by entering user ID and password,
read and search the password for given user ID.
Concepts used:
import, csv module, open(), for loop, if and else,
print()
Source Code:
import csv
f=open('prac10a.csv','w',newline='')
wo=csv.writer(f)
for i in range(n):
uid=int(input("Enter UserID: "))
pw=input("Enter password: ")
wo.writerow([uid,pw])
f.close()
f1=open('prac10a.csv','r')
r1_uid=input("Enter UserID to search: ")
ro=csv.reader(f1)
for i in ro:
if i[0]==r1_uid:
print("Password: ",i[-1])
f1.close()
OUTPUT:
How many records: 2
Enter UserID: 123
Enter password: uxw*32
Enter UserID: 980
Enter password: pl$%sWR
Enter UserID to search: 123
Password: uxw*32
12
11.Write a function that reads a CSVfile and creates
another CSV file with same content but with a different
delimiter.
Concepts used:
import, csv module, reader(), writer(), open(), for
loop, print()
Source Code:
import csv
f=open('prac11a.csv','w',newline='')
wo=csv.writer(f)
n=int(input("How many records: "))
for i in range(n):
a=input("Enter Value 1: ")
b=input("Enter Value 2: ")
wo.writerow([a,b])
f.close()
f=open('prac11a.csv','r',newline='')
f1=open('prac11b.csv','w',newline='')
ro=csv.reader(f)
w1=csv.writer(f1,delimiter='|')
for i in ro:
print(i)
w1.writerow(i)
f1.close()
f1=open('prac11b.csv','r',newline='')
r1=csv.reader(f1)
for j in r1:
print(j)
OUTPUT:
How many records: 2
13
Enter Value 1: a
Enter Value 2: b
Enter Value 1: c
Enter Value 2: d
['a', 'b']
['c', 'd']
['a|b']
['c|d']
14
12.Program to create CSV file and store empno., name,
salary and search any empno and display name, salary,
and if not found, appropriate message
Concepts used:
import, csv module, reader(), writer(), open(), for
loop, while loop, print()
Source Code:
import csv
f=open('prac12.csv','w',newline='')
wo=csv.writer(f)
for i in range(length):
empno=input("Enter empno: ")
name=input("Enter name: ")
sal=input("Enter salary: ")
wo.writerow([empno,name,sal])
f.close()
f=open('prac12.csv','r',newline='')
emp=input("Search empno: ")
ro=csv.reader(f)
c=0
for i in ro:
if i[0]==emp:
print("Name: ",i[1])
print("Salary: ",i[2])
break
c+=1
if c==length:
print("No such record found")
OUTPUT:
How many records: 3
Enter empno: 1
Enter name: Rahul
15
Enter salary: 10000
Enter empno: 2
Enter name: Ria
Enter salary: 15000
Enter empno: 3
Enter name: Thomas
Enter salary: 50000
Search empno: 3
Name: Thomas
Salary: 50000
16
13.Write functions:
To create a text file 'test.txt' with few lines of
text
To count the number of lines starting with 'b' in
the file 'test.txt'
To count the number of words starting with the
letter 'e' or 'g'
Concepts used:
open(), for loop, append(), writelines(), seek(),
readlines(), if and else, print()
Source Code:
f=open("test.txt",'w+')
lines=f.readlines()
b=0
for i in lines:
words=i.split()
if i[0][0]=='B' or i[0][0]=='b':
b+=1
print("No. of lines starting with b: ",b)
f.seek(0)
lines=f.readlines()
eg=0
l='eEgG'
17
for i in lines:
words=i.split()
for word in words:
if word[0] in l:
eg+=1
print("No. of words starting with E or G : ",eg)
OUTPUT:
How many lines: 3
Enter line: Bottles on the ground
Enter line: Computer Science is good
Enter line: Software engineering
No. of lines starting with b: 1
No. of words starting with E or G : 3
18
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
Concepts used:
import, pickle module, open(), dump(), load(), if else
and elif, while loop, try and except, close()
Source Code:
import pickle as p
f = open(r"TELEPHONE.dat", 'wb')
l = []
while True:
tn = int(input("Enter telephone number: "))
n = input("Enter customer name: ")
a = input("Enter area: ")
l = [tn, n, a]
p.dump(l, f)
a = input("Enter more? :")
if a == 'n':
19
break
f.close()
#menu
import pickle as p
def ins():
g = open(r"TELEPHONE.dat", 'ab')
while True:
li = eval(input("Enter a list to be inserted: "))
p.dump(li,g)
a = input("Enter more?: ")
if a == 'n':
break
g.close()
def dis():
g = open(r"TELEPHONE.dat", 'rb')
while True:
try:
r = p.load(g)
print(r)
except:
g.close()
def uptele():
g = open(r"TELEPHONE.dat", 'rb+')
20
n = int(input("Enter phone number to search record: "))
l = []
while True:
try:
r = p.load(g)
if r[0] == n:
name = input("Enter new name: ")
r[1] = name
area = input("Enter new area: ")
r[2] = area
l.append(r)
except:
g.close()
f = open(r"TELEPHONE.dat", 'wb')
for i in l:
p.dump(i,f)
f.close()
def searchno():
g = open(r"TELEPHONE.dat", 'rb')
n = int(input("Enter phone number to search: "))
while True:
try:
r = p.load(g)
if r[0] == n:
print(r)
break
except:
21
g.close()
def delname():
g = open(r"TELEPHONE.dat", 'rb+')
name = input("Enter name to search: ")
l = []
while True:
try:
r = p.load(g)
if r[1] != name:
l.append(r)
except:
g.close()
break
f = open(r"TELEPHONE.dat", 'wb')
for i in l:
p.dump(i, f)
f.close()
22
if o == 1:
ins()
elif o == 2:
dis()
elif o == 3:
uptele()
elif o == 4:
searchno()
elif o == 5:
delname()
else:
print('Invalid option')
OUTPUT:
Enter telephone number: 23432
Enter customer name: Abhay
Enter area: A1
Enter more? :y
Enter telephone number: 34543
Enter customer name: Siddharth
Enter area: A2
Enter more? :y
Enter telephone number: 45654
Enter customer name: Shubhankar
Enter area: A3
Enter more? :y
Enter telephone number: 56765
23
Enter customer name: Anas
Enter area: A4
Enter more? :n
#option-1
#option-2
24
[34543, 'Siddharth', 'A2']
[45654, 'Shubhankar', 'A3']
[56765, 'Anas', 'A4']
[78987, 'Shabarinath', 'A5']
#option-3
What do you want to do with file?
1. Insert more records
2. Read all and display
3. Update with number
4. Search with number
5. Delete with name
_______________________
3
Enter phone number to search record: 23432
Enter new name: Abhay H
Enter new area: A1
#option-4
What do you want to do with file?
1. Insert more records
2. Read all and display
3. Update with number
4. Search with number
5. Delete with name
_______________________
4
Enter phone number to search: 34543
[34543, 'Siddharth', 'A2']
25
#option-5
Concept used:
function, if else and elif, append(), pop(), peek(),
while loop, return, print()
Source Code:
def empty(st):
if len(st)==0:
return True
else:
return False
def push(st,item):
st.append(item)
top=st[-1]
st
def delete(st):
if empty(st):
return "Underflow"
else:
return st.pop()
top=st[-1]
def display(st):
if empty(st):
print("Stack Empty")
26
else:
print(st[-1],'<--Top')
for i in range(-2,-len(st)-1,-1):
print(st[i])
def peek(st):
if empty(st):
return "Stack Empty"
else:
return st[-1]
st=[]
while True:
print("----------------------------------")
print("Options:")
print("1: Add to stack")
print("2: Delete element")
print("3: Display stack")
print("4: Peek")
print("5: EXIT MENU")
if ch=='1':
item=int(input("Enter element: "))
push(st,item)
elif ch=='2':
ret=delete(st)
if ret=="Underflow":
print(ret)
else:
print("Popped item: ", ret)
elif ch=='3':
display(st)
elif ch=='4':
a=peek(st)
if a=="Stack Empty":
print(a)
27
else:
print("Topmost item: ",a)
elif ch=='5':
print("End of Program")
break
else:
print("Incorrect Choice. Try Again")
OUTPUT:
----------------------------------
Options:
1: Add to stack
2: Delete element
3: Display stack
4: Peek
5: EXIT MENU
Enter choice: 1
Enter element: 1
----------------------------------
Options:
1: Add to stack
2: Delete element
3: Display stack
4: Peek
5: EXIT MENU
Enter choice: 1
Enter element: 2
----------------------------------
Options:
1: Add to stack
2: Delete element
3: Display stack
4: Peek
5: EXIT MENU
Enter choice: 1
Enter element: 3
----------------------------------
Options:
1: Add to stack
2: Delete element
3: Display stack
28
4: Peek
5: EXIT MENU
Enter choice: 3
3 <--Top
2
1
----------------------------------
Options:
1: Add to stack
2: Delete element
3: Display stack
4: Peek
5: EXIT MENU
Enter choice: 2
Popped item: 3
----------------------------------
Options:
1: Add to stack
2: Delete element
3: Display stack
4: Peek
5: EXIT MENU
Enter choice: 4
Topmost item: 2
----------------------------------
Options:
1: Add to stack
2: Delete element
3: Display stack
4: Peek
5: EXIT MENU
Enter choice: 5
End of Program
29
16.Write a 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 integer 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, the function should return None.
Concepts used:
function, if else and elif, append(), pop(), peek(),
while loop, return, print()
Source Code:
def empty(TICKET):
if len(TICKET)==0:
return True
else:
return False
def PUSH(TICKET):
d={}
tno=int(input("Enter Ticket number: "))
pname=input("Enter passenger name: ")
d['TICKETNO']=tno
d['PNAME']=pname
TICKET.append(d)
def POP(TICKET):
if empty(TICKET):
return 'None'
30
else:
elem=TICKET.pop()
print("Popped item is: ",elem)
def display(TICKET):
if empty(TICKET):
return 'None'
else:
print(TICKET[-1],'<--Top')
for i in range(-2,-len(TICKET)-1,-1):
print(TICKET[i])
TICKET=[]
while True:
print("----------------------------------")
print("Options:")
print("1: Push detail")
print("2: Delete detail")
print("3: Display details: ")
print("4: EXIT MENU")
elif ch=='2':
a=POP(TICKET)
if a=='None':
print(None)
elif ch=='3':
a=display(TICKET)
if a=='None':
print(None)
elif ch=='4':
print("End of program")
break
OUTPUT:
----------------------------------
Options:
1: Push detail
2: Delete detail
3: Display details:
4: EXIT MENU
Enter choice: 3
None
----------------------------------
31
Options:
1: Push detail
2: Delete detail
3: Display details:
4: EXIT MENU
Enter choice: 1
Enter Ticket number: 122321
Enter passenger name: Riya
----------------------------------
Options:
1: Push detail
2: Delete detail
3: Display details:
4: EXIT MENU
Enter choice: 1
Enter Ticket number: 377839
Enter passenger name: Rahul
----------------------------------
Options:
1: Push detail
2: Delete detail
3: Display details:
4: EXIT MENU
Enter choice: 1
Enter Ticket number: 398430
Enter passenger name: Thomas
----------------------------------
Options:
1: Push detail
2: Delete detail
3: Display details:
4: EXIT MENU
Enter choice: 3
{'TICKETNO': 398430, 'PNAME': 'Thomas'} <--Top
{'TICKETNO': 377839, 'PNAME': 'Rahul'}
{'TICKETNO': 122321, 'PNAME': 'Riya'}
----------------------------------
Options:
1: Push detail
2: Delete detail
3: Display details:
4: EXIT MENU
Enter choice: 2
Popped item is: {'TICKETNO': 398430, 'PNAME': 'Thomas'}
----------------------------------
Options:
32
1: Push detail
2: Delete detail
3: Display details:
4: EXIT MENU
Enter choice: 4
End of program
33
17.Program to connect with database and store record
of employee and display records
Concepts used:
import, mysql.connector module, connect(),
execute(), function, commit(), if else and elif
Source Code:
def sqldisplay():
query='select * from employee order by salary desc'
ur.execute(query)
result=ur.fetchall()
print('%10s'%'empno','%10s'%'name','%10s'%'department','\t\
t salary')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'\t\
t',r[3])
34
choice=None
while choice!=0:
print('1.Add record\n2.Display record\n0.Exit')
choice=int(input("Enter choice: "))
if choice==1:
sqlinsert()
elif choice==2:
sqldisplay()
elif choice==0:
con.close()
print('#BYE#')
else:
print('#INVALID CHOICE#')
OUTPUT:
1.Add record
2.Display record
0.Exit
Enter choice: 1
enter employee number: 101
Enter name: John Doe
Enter Department: IT
Enter salary: 75000
##DATA SAVED##
1.Add record
2.Display record
0.Exit
Enter choice: 1
enter employee number: 102
Enter name: Jane Smith
Enter Department: HR
Enter salary: 60000
##DATA SAVED##
1.Add record
2.Display record
0.Exit
Enter choice: 2
empno name department salary
101 John Doe IT 75000
102 Jane Smith HR 60000
1.Add record
2.Display record
35
0.Exit
Enter choice: 0
#BYE#
18.Program to connect with database and search
employee number un table employee and display
record, if empno not found display appropriate
message.
Concepts used:
import, mysql.connector module, cursor(),
commit(), execute, function, while loop, print(),
if else and elif
Source Code:
def sqldisplay():
query='select * from employee order by salary desc'
ur.execute(query)
result=ur.fetchall()
36
print('%10s'%'empno','%10s'%'name','%10s'%'department','\t\
t salary')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'\t\
t',r[3])
def sqlsearch():
print('\t\tEmployee searching from')
print('#'*43, end='\n\n')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter empno to search: "))
query='select * from employee order by salary
desc;'
ur.execute(query)
result=ur.fetchall()
if ur.rowcount==0:
print('Sorry! Employee not found')
else:
print('\t\tEMPNO','\t\tNAME','\t\
tDEPARTMENT','\t\tSALARY')
for row in result:
print('\t\t',row[0],'\t\t',row[1],'\t\
t',row[2],'\t\t',row[3])
ans=input("Search more? y/n")
choice=None
while choice!=0:
print('1.Add record\n2.Display record\n3.Search record\
n0.Exit')
choice=int(input("Enter choice: "))
if choice==1:
sqlinsert()
elif choice==2:
sqldisplay()
elif choice==3:
sqlsearch()
elif choice==0:
con.close()
print('#BYE#')
else:
print('#INVALID CHOICE#')
37
OUTPUT:
1.Add record
2.Display record
3.Search record
0.Exit
Enter choice: 1
enter employee number: 201
Enter name: Alice Johnson
Enter Department: Marketing
Enter salary: 55000
##DATA SAVED##
1.Add record
2.Display record
3.Search record
0.Exit
Enter choice: 1
enter employee number: 202
Enter name: Bob Williams
Enter Department: Sales
Enter salary: 60000
##DATA SAVED##
1.Add record
2.Display record
3.Search record
0.Exit
Enter choice: 3
Employee searching from
###########################################
1.Add record
2.Display record
3.Search record
38
0.Exit
Enter choice: 3
Employee searching from
###########################################
1.Add record
2.Display record
3.Search record
0.Exit
Enter choice: 0
#BYE#
39
19.Program to connect with database and update the
employee record of entered emp.no
Concepts used:
import, mysql.connector module, cursor(),
commit(), execute, function, while loop, print(),
if else and elif, break
Source Code:
def sqlinsert():
e = int(input('enter employee name: '))
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)
40
result=ur.fetchall()
print('%10s'%'empno','%10s'%'name','%10s'%'department','\t\
t salary')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'\t\
t',r[3])
def sqlsearch():
print('\t\tEmployee searching from')
print('#'*43, end='\n\n')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter empno to search: "))
query='select * from employee order by salary
desc;'
ur.execute(query)
result=ur.fetchall()
if ur.rowcount==0:
print('Sorry! Employee not found')
else:
print('\t\tEMPNO','\t\tNAME','\t\
tDEPARTMENT','\t\tSALARY')
for row in result:
print('\t\t',row[0],'\t\t',row[1],'\t\
t',row[2],'\t\t',row[3])
ans=input("Search more? y/n")
def sqlupdate():
ans='y'
while ans.lower()=='y':
eno=int(input('Enter empno to update: '))
query='select * from employee2 where
empno={}'.format(eno)
ur.execute(query)
result=ur.fetchall()
if ur.rowcount==0:
print('Sorry not found')
else:
print('\t\tEMPNO','\t\tNAME','\t\
tDEPARTMENT','\tSALARY')
for r in result:
41
print('\t\t',r[0],'\t\t',r[1],'\t\
t',r[2],'\t\t',r[3])
ans=intput('Do you want to continue? y/n: ')
if ans.lower()=='y':
d=input('Enter new department: ')
s=int(input('Enter new salary: '))
else:
break
query='update employee set dept="{}",salary={}
where empno={}'.format(d,s,eno)
ur.execute(query)
con.commit()
print("RECORD UPDATED")
ans=input("Do you want to update more records? y/n:
")
choice=None
while choice!=0:
print('1.Add record\n2.Display record\n3.Search record\
n4.Update record\n0.Exit')
choice=int(input("Enter choice: "))
if choice==1:
sqlinsert()
elif choice==2:
sqldisplay()
elif choice==3:
sqlsearch()
elif choice==4:
sqlupdate()
elif choice==0:
con.close()
print('#BYE#')
else:
print('#INVALID CHOICE#')
OUTPUT:
1.Add record
2.Display record
3.Search record
4.Update record
42
0.Exit
Enter choice: 1
enter employee number: 301
Enter name: Kevin Parker
Enter Department: IT
Enter salary: 72000
##DATA SAVED##
1.Add record
2.Display record
3.Search record
4.Update record
0.Exit
Enter choice: 2
empno name department salary
301 Kevin Parker IT 72000
1.Add record
2.Display record
3.Search record
4.Update record
0.Exit
Enter choice: 4
Enter empno to update: 301
EMPNO NAME DEPARTMENT SALARY
301 Kevin Parker IT 72000
Do you want to continue? y/n: y
Enter new department: Marketing
43
Enter new salary: 78000
RECORD UPDATED
1.Add record
2.Display record
3.Search record
4.Update record
0.Exit
Enter choice: 2
empno name department salary
301 Kevin Parker Marketing 78000
1.Add record
2.Display record
3.Search record
4.Update record
0.Exit
Enter choice: 0
#BYE#
44
20.Program to connect with database and delete the
employee record of entered emp.no
Concepts used:
import, mysql.connector module, cursor(),
commit(), execute, function, while loop, print(),
if else and elif, break
Source Code:
45
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','\
t\t salary')
for r in result:
print('%10s'%r[0],'%10s'%r[1],'%10s'%r[2],'\t\t',r[3])
def sqlsearch():
print('\t\tEmployee searching from')
print('#'*43, end='\n\n')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter empno to search: "))
query='select * from employee order by salary desc;'
ur.execute(query)
result=ur.fetchall()
if ur.rowcount==0:
print('Sorry! Employee not found')
else:
46
print('\t\tEMPNO','\t\tNAME','\t\tDEPARTMENT','\t\
tSALARY')
for row in result:
print('\t\t',row[0],'\t\t',row[1],'\t\
t',row[2],'\t\t',row[3])
ans=input("Search more? y/n")
def sqlupdate():
ans='y'
while ans.lower()=='y':
eno=int(input('Enter empno to update: '))
query='select * from employee where
empno={}'.format(eno)
ur.execute(query)
result=ur.fetchall()
if ur.rowcount==0:
print('Sorry not found')
else:
print('\t\tEMPNO','\t\tNAME','\t\tDEPARTMENT','\
tSALARY')
for r in result:
print('\t\t',r[0],'\t\t',r[1],'\t\t',r[2],'\t\
t',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
47
query='update employee set dept="{}",salary={}
where empno={}'.format(d,s,eno)
ur.execute(query)
con.commit()
print("RECORD UPDATED")
ans=input("Do you want to update more records?
y/n: ")
def sqldelete():
ans='y'
while ans.lower()=='y':
eno=int(input("Enter empno to delete: "))
query='select * from employee where
empno={}'.format(eno)
ur.execute(query)
result=ur.fetchall()
if ur.rowcount==0:
print("Sorry not found")
else:
print('\t\tEMPNO','\t\tNAME','\t\tDEPARTMENT','\
tSALARY')
for r in result:
print('\t\t',r[0],'\t\t',r[1],'\t\t',r[2],'\t\
t',r[3])
ans=input('Do you want to continue? y/n: ')
if ans.lower()=='y':
query='delete from employee where
empno={}'.format(eno)
ur.execute(query)
print('RECORD DELETED')
48
break
choice=None
while choice!=0:
print('1.Add record\n2.Display record\n3.Search record\
n4.Update record\n5.Delete record\n0.Exit')
choice=int(input("Enter choice: "))
if choice==1:
sqlinsert()
elif choice==2:
sqldisplay()
elif choice==3:
sqlsearch()
elif choice==4:
sqlupdate()
elif choice==5:
sqldelete()
elif choice==0:
con.close()
print('#BYE#')
else:
print('#INVALID CHOICE#')
OUTPUT:
1.Add record
2.Display record
3.Search record
4.Update record
49
5.Delete record
0.Exit
Enter choice: 1
enter employee no: 101
Enter name: John Doe
Enter Department: HR
Enter salary: 50000
##DATA SAVED##
1.Add record
2.Display record
3.Search record
4.Update record
5.Delete record
0.Exit
Enter choice: 5
Enter empno to delete: 101
EMPNO NAME DEPARTMENT SALARY
101 John Doe HR 50000
Do you want to continue? y/n: y
RECORD DELETED
1.Add record
2.Display record
3.Search record
4.Update record
5.Delete record
0.Exit
50
Enter choice: 2
empno name department salary
1.Add record
2.Display record
3.Search record
4.Update record
5.Delete record
0.Exit
Enter choice: 0
#BYE#
51
MySQL
52
SQL program 1
TABLE:FLIGHTS
Column name Data type Size Constraint
FL NO CHAR 10 PRIMARY KEY
NO_OF_STOPS INTEGER
53
| 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.04 sec)
TABLE:FARE
Column Name Data Type Size Constraint
FL_NO CHAR 10 PRIMARY KEY
AIRLINES VARCHAR 20 NOT NULL
FARE DECIMAL 10,2 NOT NULL
TAX DECIMAL 10,2 NOT NULL
54
mysql> insert into flights
values('IC301','MUMBAI','DELHI',8,0);
Query OK, 1 row affected (0.07 sec)
mysql> insert into flights
values('IC799','BANGALORE','DELHI',2,1);
Query OK, 1 row affected (0.07 sec)
55
mysql> insert into flights
values('IC701','DELHI','AHMEDABAD',4,0);
Query OK, 1 row affected (0.05 sec)
TABLE:FARE
FL_NO AIRLINES FARE TAX
IC701 INDIAN 6500 10
AIRLINES
MU499 SAHARA 9400 5
56
AIRLINES
MC101 DECCAN 3500 4
AIRLINES
57
mysql> insert into FARE values("IC799","INDIAN
AIRLINES",1050,10);
Query OK, 1 row affected (0.07 sec)
58
| IC899 | INDIAN AIRLINES | 8300.00 | 4.00 |
| MC101 | DECCAN AIRLINES | 3500.00 | 4.00 |
| MU499 | SAHARA | 9400.00 | 5.00 |
+-------+-----------------+----------+-------+
7 rows in set (0.00 sec)
59
+-----------------+------------+
1 row in set (0.03 sec)
60
mysql> select count(distinct(AIRLINES)) from FARE;
+---------------------------+
| count(distinct(AIRLINES)) |
+---------------------------+
| 4 |
+---------------------------+
1 row in set (0.03 sec)
61
mysql> select * from fare;
+-------+-----------------+----------+-------+
| FL_NO | AIRLINES | FARE | TAX |
+-------+-----------------+----------+-------+
| AM501 | JET AIRWAYS | 13450.00 | 8.00 |
| IC302 | INDIAN AIRLINES | 4300.00 | 9.00 |
| IC701 | INDIAN AIRLINES | 6500.00 | 10.00 |
| IC799 | INDIAN AIRLINES | 1050.00 | 10.00 |
| IC899 | INDIAN AIRLINES | 8300.00 | 4.00 |
| MC101 | DECCAN AIRLINES | 3500.00 | 4.00 |
| MU499 | SAHARA | 9600.00 | 5.00 |
+-------+-----------------+----------+-------+
7 rows in set (0.00 sec)
62
| MU499 | SAHARA | 10080.00 |
+-------+-----------------+----------------------+
7 rows in set (0.00 sec)
63
+-------+-----------+---------+------------+-------------+
| IC302 | DELHI | MUMBAI | 8 | 0 |
| MC101 | INDORE | MUMBAI | 3 | 0 |
+-------+-----------+---------+------------+-------------+
2 rows in set (0.01 sec)
64
+-------+-----------------+----------+
| FL_NO | FLIGHT_NAME | FARE |
+-------+-----------------+----------+
| AM501 | JET AIRWAYS | 13450.00 |
| IC302 | INDIAN AIRLINES | 4300.00 |
| IC701 | INDIAN AIRLINES | 6500.00 |
| IC799 | INDIAN AIRLINES | 1050.00 |
| IC899 | INDIAN AIRLINES | 8300.00 |
| MC101 | DECCAN AIRLINES | 3500.00 |
| MU499 | SAHARA | 9600.00 |
+-------+-----------------+----------+
7 rows in set (0.00 sec)
SQL program 2
Table SCHOOL
Column Name Data Type Size Constraints
Code Integer Primary key
Teachername Varchar 20 Not null
65
Subject Char 20 Not null
DOJ Date Not null
Periods Integer
Experience Integer
Table ADMIN
Column name Data Type Size Constraints
Code Integer Primary Key
66
Gender Varchar 8 Not null
Designation Char 20 Not null
Table SCHOOL
Code Teachernam Subject DOJ Period Experienc
e s e
1001 Ravi English 2001/12/0 24 10
Shankar 3
1009 Priya Raj Physics 1998/09/1 26 12
2
1203 Lasa Anand English 2000/04/0 27 5
9
1045 Yasraj Maths 2000/08/2 24 15
4
1123 Gagan Physics 1999/07/1 28 3
6
1167 Umesh Chemistry 1998/05/1 22 5
1
67
-> (1203,"Lasa Anand","English","2000/04/09",27,5),
-> (1045,"Yasraj","Maths","2000/08/24",24,15),
-> (1123,"Gagan","Physics","1999/07/16",28,3),
-> (1167,"Umesh","Chemistry","1998/05/11",22,5);
Query OK, 5 rows affected (0.08 sec)
Records: 5 Duplicates: 0 Warnings: 0
Table ADMIN
Code Gender Desgination
1001 Male Vice Principal
1203 Female Coordinator
1009 Female Coordinator
1045 Male HOD
1123 Male Senior Teacher
1167 Male Senior Teacher
68
-> (1203,"Female","Coordinator"),
-> (1009,"Female","Coordinator"),
-> (1045,"Male","HOD"),
-> (1123,"Male","Senior Teacher"),
-> (1167,"Male","Senior Teacher");
Query OK, 6 rows affected (0.05 sec)
Records: 6 Duplicates: 0 Warnings: 0
69
mysql> select * from school order by Teachername desc;
+------+--------------+-----------+------------+---------
+------------+
| Code | Teachername | Subject | DOJ | Periods |
Experience |
+------+--------------+-----------+------------+---------
+------------+
| 1045 | Yasraj | Maths | 2000-08-24 | 24 |
15 |
| 1167 | Umesh | Chemistry | 1998-05-11 | 22 |
5 |
| 1001 | Ravi Shankar | English | 2001-12-03 | 24 |
10 |
| 1009 | Priya Raj | Physics | 1998-09-12 | 26 |
12 |
| 1203 | Lasa Anand | English | 2000-04-09 | 27 |
5 |
| 1123 | Gagan | Physics | 1999-07-16 | 28 |
3 |
+------+--------------+-----------+------------+---------
+------------+
6 rows in set (0.00 sec)
70
6 rows in set (0.00 sec)
71
Rows matched: 2 Changed: 2 Warnings: 0
73
Display the highest experience in each subject
74
mysql> select Designation,count(Teachername) from
school,admin where SCHOOL.Code=ADMIN.Code group by
designation;
+----------------+--------------------+
| Designation | count(Teachername) |
+----------------+--------------------+
| Vice Principal | 1 |
| Coordinator | 2 |
| HOD | 1 |
| Senior Teacher | 2 |
+----------------+--------------------+
4 rows in set (0.00 sec)
75
| 1203 | Lasa Anand | English | 2000-04-09 | 27 |
7 |
+------+--------------+-----------+------------+---------
+------------+
4 rows in set (0.00 sec)
SQL program 3
Table CLUB
COLUMN NAME DATA TYPE SIZE CONSTRAINTS
Coach_ID Integer 4 Primary Key
Sports Varchar 20
DateOfApp Date
Gender Char 2
76
| DateOfApp | date | YES | | NULL | |
| Pay | decimal(8,3) | YES | | NULL | |
| Gender | char(2) | YES | | NULL | |
+-----------+--------------+------+-----+---------+-------+
7 rows in set (0.04 sec)
Insert the following values into table.
Table COACH
CoachI Cname Age Sports DateOfAp Pay Gende
D p r
1 Kukrej 35 Karate 27/03/199 1000 M
a 6
2 Ravina 34 Karate 20/01/199 1200 F
8
3 Karan 34 Squash 19/02/199 2000 M
8
4 Tarun 33 Basketbal 01/01/199 1500 M
l 8
5 Zubin 36 Swimming 12/01/199 750 M
8
6 Ketaki 36 Swimming 24/02/199 800 F
8
7 Amkita 39 Squash 20/02/199 2200 F
8
8 Zareen 37 Karate 22/02/199 1100 F
8
9 Kush 41 Swimming 13/01/199 900 M
8
10 Saliya 37 Basketbal 19/02/199 3700 M
l 8
77
Query OK, 10 rows affected (0.11 sec)
Records: 10 Duplicates: 0 Warnings: 0
78
Query OK, 0 rows affected (0.38 sec)
Records: 0 Duplicates: 0 Warnings: 0
79
| salary | decimal(10,3) | YES | | NULL |
|
| Gender | char(2) | YES | | NULL |
|
| address | varchar(20) | YES | | NULL |
|
+-----------+---------------+------+-----+---------
+-------+
8 rows in set (0.00 sec)
80
| Karan |
| Saliya |
| Zareen |
| Ravina |
| Kush |
| Zubin |
| Tarun |
| Kukreja |
+-----------+
10 rows in set (0.16 sec)
81
+------------------------+
1 row in set (0.01 sec)
82
| min(Age) | max(Age) |
+----------+----------+
| 34 | 39 |
+----------+----------+
1 row in set (0.00 sec)
83
SQL program 4
84
-> ('MB006', 'Oppo', 'SelfieEx', 8500, '2010/08/21');
Query OK, 5 rows affected (0.06 sec)
Records: 5 Duplicates: 0 Warnings: 0
85
| M_Qty | int | YES | | NULL | |
| M_Supplier | varchar(20) | YES | | NULL | |
+------------+-------------+------+-----+---------+-------+
4 rows in set (0.04 sec)
86
+-----------+----------+---------+
| Sony | XperiaM | 7500 |
| Micromax | Unite3 | 4500 |
| Samsung | Galaxy | 4500 |
| Nokia | N1100 | 2250 |
| Oppo | SelfieEx | 8500 |
+-----------+----------+---------+
5 rows in set (0.01 sec)
87
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)
SQL program 5
88
| CITY | varchar(15) | YES | | NULL | |
| HIREDATE | date | YES | | NULL | |
| SALARY | int | YES | | NULL | |
+----------+-------------+------+-----+---------+-------+
5 rows in set (0.08 sec)
mysql> insert into TRAINER values
-> (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);
Query OK, 6 rows affected (0.08 sec)
Records: 6 Duplicates: 0 Warnings: 0
89
Table COURSE
CID CNAME FEES STARTDATE TID
C201 AGDCA 12000 2018/07/02 101
C202 ADCA 15000 2018/07/15 103
C203 DCA 10000 2018/10/01 102
C204 DDTP 9000 2018/09/15 104
C205 DHN 20000 2018/08/01 101
C206 O LEVEL 18000 2018/07/25 105
90
-> ('C206', 'O Level', 18000, '2018/07/25', 105);
Query OK, 6 rows affected (0.11 sec)
Records: 6 Duplicates: 0 Warnings: 0
91
| Richa | Mumbai | 95000 |
| Anamika | Delhi | 80000 |
+------------+------------+--------+
2 rows in set (0.12 sec)
92
+------------+----------+
| CITY | count(*) |
+------------+----------+
| Mumbai | 2 |
| Delhi | 2 |
| Chandigarh | 1 |
| Chennai | 1 |
+------------+----------+
4 rows in set (0.04 sec
93