Python Practical Record Anna
Python Practical Record Anna
Signature
Signature Mr. Gulshan Sharma
Dr. Urmila Vajpai
( PGT Computer Science )
( Principal )
1
Acknowledgement
2
At last I shall heartily thank to my
parents & for their love, care, concern & lots of
inspirations.
Adya Sri
Class : 12th –
E
Sacred Hearts Sr. Sec.
Public School
Table of Content
3
14 Recursive function to search an element using Linear Search
15 Recursive function to search an element using Binary Search
16 Traversal in a Linear List – manipulation of elements
17 Traversal in a Linear List – displaying largest and smallest element of the List
18 Traversal in a Linear List – reversing the elements of a List
19 Traversal in a Linear List – swapping of the elements
20 Insertion in a Sorted Linear List
21 Deletion of a given element in a Linear List
22 Deletion of odd elements for a Linear List
23 Merging of two Linear Lists
24 Merging of two Linear List in reverse order
25 Sorting a Linear List using Bubble Sort
26 Sorting a Linear List using Selection Sort
27 Traversal in a Nested List – manipulation of elements
28 Traversal in a Nested List – sum of even elements of a nested List
29 Nested List – displaying elements of upper right triangle in a square matrix
30 Nested List – displaying elements of middle row and column of a square matrix
31 Nested List – displaying elements of both the diagonals in a square matrix
32 Nested List – displaying elements present on the boundary of a square matrix
33 Nested List – transpose of a square matrix
34 Implementing a Stack using a List
35 Implementing a Queue using a List
36 Text File – Writing and Reading data
37 Searching characters in a text file
38 Searching words in a text file
39 Searching lines in a text file
40 Modification in a text file
41 Deletion in a text file
42 Binary File – Writing and Reading data
43 Searching data in a binary file
44 Modifying data in a binary file
45 Searching of an element in a Linear List using Iteration – Linear Search
4
46 Searching of an element in a Linear List using Iteration – Binary Search
47 Problem of SQL – Queries
48 Line Chart
49 Bar Chart
50 Pie Chart
51 5 Problems of SQL – SQL Queries
52 Integrating MySQL with Python to write data in a table
53 Integrating MySQL with Python to display data from a table
54 Django based web server to parse a user request (POST), write data to CSV file.
5
PROGRAM 1 : Read number of units from user and calculate the electricity bill as follows–
Units Charges
<=100 500
>100 and <=200 2 per extra unit over 100
>200 and <=300 4 per extra unit over 200
>300 6 per extra unit over 300
def calculate(n):
if n <= 100 :
c = 500
elif n > 100 and n <= 200:
c = 500 + 2 * (n - 100)
elif n > 200 and n <= 300:
c = 500 + 2 * 100 + 4 * (n - 200)
else:
c = 500 + 2 * 100 + 4 * 100 + 6 * (n - 200)
return c
6
n = int (input("Enter Number of Units : "))
print("Electricity Bill : ", calculate(n))
stu={}
per={}
n=int(input("Enter Number of Students : "))
for i in range(n):
r = int(input("Enter Roll Number : "))
n = input("Enter Name : ")
m = int(input("Enter Marks : "))
per['Name']=n
per['Marks']=m
stu[r]=dict(per)
print(stu)
ele = int(input("Enter roll no to be search : "))
for i in stu:
if ele == i:
print("Roll Number : ",i)
7
print("Name : ",stu[i]['Name'])
print("Marks : ",stu[i]['Marks'])
Roll Number : 4
Name : Mukesh
Marks : 88
def show(n):
if n<=1:
return n
else:
return n + show(n-1)
8
Enter Limit : 100
def abc(n):
if n==1:
return 1
else:
return n * n + abc(n-1)
n = int(input("Enter a Number : "))
s = abc(n)
print(s)
Enter a Number : 5
55
def abc(n):
if n==1:
return 1
else:
return n * abc(n-1)
9
Enter a Number : 5
Factorial is : 120
def abc(m,n):
if n==1:
return m
else:
return m * abc(m,n-1)
m = int(input("Enter Value of m : "))
n = int(input("Enter Value of n : "))
s = abc(m, n)
print("m to the Power n is : ", s)
Enter Value of m : 2
Enter Value of n : 5
m to the Power n is : 32
10
Enter a Number : 78
GCD : 6
def abc(n):
if n<=1:
return n
else:
return abc(n-1) + abc(n-2)
Enter limit : 8
n = int(input("Enter a no : "))
if abc(n,1,0) == 1:
print("Prime no")
11
else:
print("Not Prime")
Enter a no : 17
Prime no
def abc(a,s):
if s == len(a):
return
else:
abc(a,s+1)
print(a[s], end=' ')
Reversed String : N O H T Y P
12
return abc(a, s+1, b)
21
13
print("Largest element = ",p)
Largest element = 87
found at 3
14
else:
return abc(a, ele, b, m-1)
Element found at : 6
def show(a):
for i in range(len(a)):
if a[i] % 2 == 0:
a[i] = a[i] // 2
else:
a[i] = a[i] * 3
print("List after Modification : ", a)
#----------Main------------------
a = []
s = int(input("Enter Size of a List : "))
print("Enter element of the List")
for i in range(s):
a.append(int(input("Enter an element : ")))
print("Original List : ", a)
show(a)
15
Enter Size of a List : 5
Enter an element : 11
Enter an element : 22
Enter an element : 33
Enter an element : 44
Enter an element : 55
PROGRAM 17 : Traversal in a Linear List – displaying largest and smallest element of the
List
def show(a):
mx = mn = a[0]
for i in range(1, len(a)):
if a[i] > mx:
16
mx = a[i]
elif a[i] < mn:
mn = a[i]
print("Largest element is : " , mx)
print("Smallest element is : " , mn)
#----------Main------------------
a = []
s = int(input("Enter Size of a List : "))
print("Enter element of the List")
for i in range(s):
a.append(int(input("Enter an element : ")))
print("Original List : ", a)
show(a)
def show(a):
for i in range(len(a)//2):
a[i], a[len(a)-1-i] = a[len(a)-1-i], a[i]
print("Reversed list is : " , a)
#----------Main------------------
a = []
17
s = int(input("Enter Size of a List : "))
print("Enter element of the List")
for i in range(s):
a.append(int(input("Enter an element : ")))
print("Original List : ", a)
show(a)
PROGRAM 19 : Traversal in a Linear List – swapping of first half elements with next half
elements of a list
def show(a):
for i in range(len(a)//2):
a[i], a[len(a)//2+i] = a[len(a)//2+i], a[i]
print("Reversed list is : " , a)
#----------Main------------------
18
a = []
s = int(input("Enter Size of a List : "))
print("Enter element of the List")
for i in range(s):
a.append(int(input("Enter an element : ")))
print("Original List : ", a)
show(a)
19
break
if p == -1 :
a.append(ele)
else:
a.insert(p,ele)
print("List after Insertion : ", a)
#----------Main------------------
a = []
s = int(input("Enter Size of a List : "))
print("Enter element of the List")
for i in range(s):
a.append(int(input("Enter an element : ")))
ele = int(input("Enter element to be inserted : "))
print("Original List : ", a)
Insertion(a, ele)
Enter an element : 10
Enter an element : 20
Enter an element : 30
Enter an element : 40
Enter an element : 50
Enter an element : 60
Enter an element : 70
20
p = i
break
a.pop(p)
print("List after Deletion : ", a)
#----------Main------------------
a = []
s = int(input("Enter Size of a List : "))
print("Enter element of the List")
for i in range(s):
a.append(int(input("Enter an element : ")))
ele = int(input("Enter element to be deleted : "))
print("Original List : ", a)
Deletion(a, ele)
Enter an element : 10
Enter an element : 80
Enter an element : 30
Enter an element : 20
Enter an element : 90
Enter an element : 60
Enter an element : 50
def Deletion(a):
i = 0
while i <= len(a)-1:
21
if a[i]%2 == 0:
a.pop(i)
i+=1
print("List after Deletion : ", a)
#----------Main------------------
a = []
s = int(input("Enter Size of a List : "))
print("Enter element of the List")
for i in range(s):
a.append(int(input("Enter an element : ")))
print("Original List : ", a)
Deletion(a)
Enter an element : 5
Original List : [1, 2, 3, 4, 5]
List after Deletion : [1, 3, 5]
22
print("Second List : ", b)
print("Merged List : ", c)
#----------Main------------------
a = []
b = []
s = int(input("Enter Size of first List : "))
print("Enter element of First List")
for i in range(s):
a.append(int(input("Enter an element : ")))
s = int(input("Enter Size of Second List : "))
print("Enter element of Second List")
for i in range(s):
b.append(int(input("Enter an element : ")))
Merging(a, b)
23
c = a +b
print("First List : ", a)
print("Second List : ", b)
print("Merged List : ", c)
#----------Main------------------
a = []
b = []
s = int(input("Enter Size of first List : "))
print("Enter element of First List")
for i in range(s):
a.append(int(input("Enter an element : ")))
s = int(input("Enter Size of Second List : "))
print("Enter element of Second List")
for i in range(s):
b.append(int(input("Enter an element : ")))
Merging(a, b)
def BubbleSort(a):
for i in range(len(a)):
24
for j in range(len(a)-1-i):
if a[j]>a[j+1]:
a[j] , a[j+1] = a[j+1] , a[j]
print(a)
#----------Main------------------
a = []
s = int(input("Enter Size of a List : "))
print("Enter element of the List")
for i in range(s):
a.append(int(input("Enter an element : ")))
BubbleSort("Sorted List is : ", a)
Enter an element : 5
Enter an element : 1
Enter an element : 4
Enter an element : 2
Enter an element : 8
def SelectionSort(a):
for i in range(len(a)):
small = a[i]
25
p = i
for j in range(i+1, len(a)):
if a[j] < small:
small = a[j]
p = j
a[i], a[p] = a[p], a[i]
Enter an element : 64
Enter an element : 25
Enter an element : 12
Enter an element : 22
Enter an element : 11
26
for i in range(R):
for j in range(C):
if A[i][j] % 2 == 0:
A[i][j] = A[i][j] // 2
else:
A[i][j] = A[i][j] * 3
A = []
R = int(input("Enter No of Rows : "))
C = int(input("Enter No of Columns : "))
for i in range(R):
B = []
for j in range(C):
n=int(input("Enter an element : "))
B.append(n)
A.append(B)
27
Enter No of Rows : 3
Enter No of Columns : 3
Enter an element : 1
Enter an element : 2
Enter an element : 3
Enter an element : 4
Enter an element : 5
Enter an element : 6
Enter an element : 7
Enter an element : 8
Enter an element : 9
Original List is :
123
456
789
Modified List is :
319
2 15 3
21 4 27
28
def show(A, R, C):
s = 0
for i in range(R):
for j in range(C):
if A[i][j] % 2 == 0:
s = s + A[i][j]
print("Sum of Even Elements : ", s)
A = []
R = int(input("Enter No of Rows : "))
C = int(input("Enter No of Columns : "))
for i in range(R):
B = []
for j in range(C):
n=int(input("Enter an element : "))
B.append(n)
A.append(B)
29
Enter No of Rows : 3
Enter No of Columns : 3
Enter an element : 1
Enter an element : 2
Enter an element : 3
Enter an element : 4
Enter an element : 5
Enter an element : 6
Enter an element : 7
Enter an element : 8
Enter an element : 9
Original List is :
123
456
789
Sum of Even Elements : 20
30
PROGRAM 29 : Nested List – displaying elements of upper right triangle in a square matrix
A = []
R = int(input("Enter No of Rows : "))
C = int(input("Enter No of Columns : "))
for i in range(R):
B = []
for j in range(C):
n=int(input("Enter an element : "))
B.append(n)
A.append(B)
31
Output of the Program :
Enter No of Rows : 3
Enter No of Columns : 3
Enter an element : 1
Enter an element : 2
Enter an element : 3
Enter an element : 4
Enter an element : 5
Enter an element : 6
Enter an element : 7
Enter an element : 8
Enter an element : 9
Original List is :
123
456
789
32
PROGRAM 30 : Nested List – displaying elements of middle row and column of a square
matrix
A = []
R = int(input("Enter No of Rows : "))
C = int(input("Enter No of Columns : "))
for i in range(R):
B = []
for j in range(C):
n=int(input("Enter an element : "))
B.append(n)
A.append(B)
33
Output of the Program :
Enter No of Rows : 3
Enter No of Columns : 3
Enter an element : 1
Enter an element : 2
Enter an element : 3
Enter an element : 4
Enter an element : 5
Enter an element : 6
Enter an element : 7
Enter an element : 8
Enter an element : 9
Original List is :
123
456
789
34
PROGRAM 31 : Nested List – displaying elements of both the diagonals in a square matrix
A = []
R = int(input("Enter No of Rows : "))
C = int(input("Enter No of Columns : "))
for i in range(R):
B = []
for j in range(C):
n=int(input("Enter an element : "))
B.append(n)
A.append(B)
35
Output of the Program :
Enter No of Rows : 3
Enter No of Columns : 3
Enter an element : 1
Enter an element : 2
Enter an element : 3
Enter an element : 4
Enter an element : 5
Enter an element : 6
Enter an element : 7
Enter an element : 8
Enter an element : 9
Original List is :
123
456
789
36
PROGRAM 32 : Nested List – displaying elements present on the boundary of a square
matrix
A = []
R = int(input("Enter No of Rows : "))
C = int(input("Enter No of Columns : "))
for i in range(R):
B = []
for j in range(C):
n=int(input("Enter an element : "))
B.append(n)
A.append(B)
37
Output of the Program :
Enter No of Rows : 3
Enter No of Columns : 3
Enter an element : 1
Enter an element : 2
Enter an element : 3
Enter an element : 4
Enter an element : 5
Enter an element : 6
Enter an element : 7
Enter an element : 8
Enter an element : 9
Original List is :
123
456
789
38
PROGRAM 33 : Nested List – transpose of a square matrix
A = []
R = int(input("Enter No of Rows : "))
C = int(input("Enter No of Columns : "))
for i in range(R):
B = []
for j in range(C):
n=int(input("Enter an element : "))
B.append(n)
A.append(B)
39
Output of the Program :
Enter No of Rows : 3
Enter No of Columns : 3
Enter an element : 1
Enter an element : 2
Enter an element : 3
Enter an element : 4
Enter an element : 5
Enter an element : 6
Enter an element : 7
Enter an element : 8
Enter an element : 9
Original List is :
123
456
789
Transpose of List :
147
258
369
40
PROGRAM 34 : Implementing a Stack using a List
def Push(a):
ele = int(input("Enter an element to be inserted in Stack : "))
a.append(ele)
def Pop(a):
if a == []:
print("Underflow")
else:
print("Popped element is : ", a.pop())
def Peek(a):
if a == []:
print("Underflow")
else:
print("element at the top : ", a[len(a)-1])
def Display(a):
if a == []:
print("Underflow")
else:
for i in range(len(a)-1,-1,-1):
print(a[i])
#-------------------------------
MAIN----------------------------------
a = []
top = None
while True:
print("Stack Operatons")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Exit")
ch = int(input("Enter Choice : "))
if ch == 1:
Push(a)
41
elif ch == 2:
Pop(a)
elif ch == 3:
Peek(a)
elif ch == 4:
Display(a)
elif ch == 5:
break
42
Enter Choice : 4
88
33
66
def Enqueue(a):
ele = int(input("Enter an element to be inserted in Queue : "))
a.append(ele)
def Dequeue(a):
if a == []:
print("Underflow")
else:
print("Deleted element is : ", a.pop(0))
def Peek(a):
if a == []:
print("Underflow")
else:
print("element at the Front : ", a[0])
def Display(a):
if a == []:
print("Underflow")
else:
for i in range(len(a)):
print(a[i], end = " , ")
#-------------------------
MAIN---------------------------------------
a = []
while True:
print("\n1Queue Operatons")
print("1. Insert")
print("2. Delete")
print("3. Peek")
print("4. Display")
print("5. Exit")
ch = int(input("Enter Choice : "))
if ch == 1:
Enqueue(a)
43
elif ch == 2:
Dequeue(a)
elif ch == 3:
Peek(a)
elif ch == 4:
Display(a)
elif ch == 5:
break
44
Queue Operatons 2. Delete
1. Insert 3. Peek
2. Delete 4. Display
3. Peek 5. Exit
4. Display
5. Exit Enter Choice : 5
45
Enter a Line : This is First line
Enter a Line : This is Second line
Enter a Line : This is Third line
Enter a Line : This is Forth line
def abc():
file=open('data.txt','r')
content =file.read()
print(content)
x=y=z=0
for i in content:
if i.isupper():
x+=1
if i.islower():
y+=1
else:
z+=1
print ("No. of Upper Case Characters are : ", x)
print ("No. of Lower Case Characters are : ", y)
print ("No. of OtherCharacters are : ", z)
file.close()
abc()
46
Output of the Program :
def abc():
x = 0
file=open('data.txt','r')
data=file.readlines()
for line in data:
print(line)
word = line.split()
for i in word:
if i == 'is':
x+=1
file.close()
print("is counted : ", x)
abc()
47
Output of the Program :
PROGRAM 39 : Searching lines in a text file – display the line which contains ‘Second’ as
sub-string.
def abc():
file=open('data.txt','r')
data=file.readlines()
for line in data:
if 'Second' in line:
print(line)
file.close()
abc()
48
def abc():
file=open('data.txt','r')
content =file.read()
print(content)
print()
for i in content:
if i == 'T':
print('C', end = '')
else:
print(i, end = '')
file.close()
abc()
def abc():
file=open('data.txt','r')
content =file.read()
word = content.split()
b = ''
for i in word:
if i != 'This':
b = b +' '+ i
file.close()
file=open('data.txt','w')
file.write(b)
file.close()
file=open('data.txt','r')
content =file.read()
print(content)
49
file.close()
abc()
PROGRAM 42 : Binary File – Writing and Reading data of a dictionary having names of
three students.
import pickle
def writing():
n = {1:'ram',2:'mohan', 3:'shyam'}
file = open('bylist.dat', 'wb')
pickle.dump(n,file)
print("Data added successfully")
file.close()
def reading():
file = open('bylist.dat', 'rb')
n = pickle.load(file)
print(n)
file.close()
50
writing()
reading()
PROGRAM 43 : Searching data in a binary file. Writing data of student in the form of
dictionary and displaying records of those students who are having marks greater than 90.
import pickle
def writing():
s = int(input("Enter Number of Students : "))
file = open('bylist.dat', 'wb')
d ={}
for i in range(s):
r = int(input("Enter Roll No : "))
n = input("Enter Name :")
m = int(input("Enter Marks : "))
d['rollno']=r
d['name']=n
51
d['marks']=m
pickle.dump(d,file)
print("Data added successfully")
file.close()
def reading():
file = open('bylist.dat', 'rb')
try:
while True:
d = pickle.load(file)
if d['marks']>90:
print(d)
except EOFError :
file.close()
writing()
reading()
52
Enter Number of Students : 3
Enter Roll No : 1
Enter Marks : 95
Enter Roll No : 2
Enter Marks : 34
Enter Roll No : 3
Enter Marks : 93
53
import pickle
def modification():
file = open('bylist.dat', 'rb')
try:
while True:
d = pickle.load(file)
if d['marks']>90:
d['marks'] = 100
print(d)
except EOFError :
file.close()
modification()
54
PROGRAM 45 : Searching of an element in a Linear List using Linear Search method using
iteration.
Enter an element : 55
Enter an element : 17
Enter an element : 83
Enter an element : 26
Enter an element : 93
Enter an element : 14
55
PROGRAM 46 : Searching of an element in a Linear List using Binary Search method using
iteration.
def BinarySearch(a, ele):
p = -1
b = 0
l = len(a)-1
while b<=l:
m = (b + l)//2
if ele == a[m]:
p = m
break
elif ele > a[m]:
b = m+1
else:
l = m-1
if p == -1:
print("Element not found")
else:
print("Element Found at : ", p+1)
#----------Main------------------
a = []
s = int(input("Enter Size of a List : "))
print("Enter element of the List in Ascending Order ")
for i in range(s):
a.append(int(input("Enter an element : ")))
ele = int(input("Enter element to be search : "))
BinarySearch(a, ele)
56
Enter Size of a List : 9
Enter element of the List in Ascending Order
Enter an element : 5
Enter an element : 12
Enter an element : 17
Enter an element : 23
Enter an element : 38
Enter an element : 44
Enter an element : 77
Enter an element : 84
Enter an element : 90
import matplotlib.pyplot as pl
import numpy as np
x = np.linspace(0, 10, 1000)
pl.plot(x, np.sin(x), color = 'green', linewidth = 4, linestyle =
'dotted')
pl.plot(x, np.cos(x), color = 'red', linewidth = 4, linestyle =
'dashed')
pl.title("Line Chart")
pl.xlabel("Natural Numbers")
pl.ylabel("Sin / Cos Values")
pl.show()
57
PROGRAM 48 : Bar chart
import matplotlib.pyplot as pl
import numpy as np
R = np.array([1, 2, 3, 4])
T1 = [ 45, 80, 25, 95 ]
T2 = [ 75, 92, 58, 65 ]
pl.bar(R, T1, color = 'red', width = 0.3)
pl.bar(R+0.3, T2, color = 'green', width = 0.3)
pl.xticks(R,['James', 'Alice', 'Raj', 'Sumit'])
pl.title("Report Card")
pl.xlabel("Name of Students")
pl.ylabel("Marks")
pl.show()
58
Output of the Program :
import matplotlib.pyplot as pl
M = [55, 10, 26, 74]
N = ['Atul', 'James', 'Sanjeev', 'Anurag']
C = ['pink', 'red', 'yellow', 'cyan']
E = [0, 0.3, 0, 0]
pl.pie( M, labels = N, colors = C, explode = E, autopct = "%1.1f%
%" )
pl.show()
59
60
61
Consider the following tables and write SQL commands for the given statements
1) Table : PRODUCT
P_ID ProductName Manufacturer Price
TP01 Talcom Powder LAK 40
FW05 Face Wash ABC 45
BS01 Bath Soap ABC 55
SH06 Shampoo XYZ 120
FW12 Face Wash XYZ 95
Table : CLIENT
C_ID ClientName City P_ID
01 Cosmetic Shop Delhi FW05
06 Total Health Mumbai BS01
12 Live Life Delhi SH06
12 Pretty Woman Delhi FW12
16 Dreams Banglore TP01
62
2) To display the details of products whose Price is in the range of 50 to 100 ( Both values included ).
3) To display the ClientName, City from table CLIENT and ProductName and Price from table
PRODUCT, with their corresponding matching P_ID.
4) To increase the price of all Products by 10 which are having Manufacturer ABC.
5) Give outputs:
a. select Count ( distinct City ) from Client;
b. select Manufacturer, MAX (Price) from Product Group By Manufacturer;
c. select ClientName, Manufacturer from Client, Product where Client . P_ID = Product . P_ID;
d. select ProductName, Price * 4 from Product;
Answers
d. ProductName Price * 4
Talcom Powder 160
Face Wash 180
Bath Soap 220
Shampoo 480
Face Wash 380
2) Table : Emp
Empid Firstname Lastname Address City
010 Ravi Kumar Raj nagar GZB
152 Sam Tones 33 Elm St. Paris
215 Sarah Ackerman 440 U.S. 110 Upton
244 Manila Sengupta 24 Friends street New Delhi
300 Robert Samuel 9 Fifth Cross Washington
335 Ritu Tondon Shastri Nagar GZB
400 Rachel Lee 121 Harrison St. New York
Sal
Empid Salary Benefits Designation
010 75000 15000 Manager
152 80000 25000 Director
215 75000 12500 Manager
244 50000 12000 Clerk
300 45000 10000 Clerk
335 40000 10000 Clerk
63
400 32000 7500 Salesman
(i) To show firstname, address and city of all employees living in Paris
(ii) To display the content of Employees table having empid > 200 in descending order of Firstname.
(iii) To display the firstname and total salary of all managers from the tables Emp and sal , where total
salary is calculated as salary+benefits.
(iv) To display the maximum salary among managers and clerks from the table sal.
(v) Give the Output of following SQL commands:
(i) Select count(distinct designation) from sal;
(ii) Select designation, Count(*) from sal group by designation having count(*) >2;
(iii) Select sum(benefits) from sal where designation =’Clerk’;
(iv) Select distinct City from Emp;
Answers
I. Count(distinct designation)
4
Table : CUSTOMER
C_ID CustomerName City I_ID
01 N Roy Delhi LC03
06 H Singh Mumbai PC03
12 R Pandey Delhi PC06
15 C Sharma Delhi LC03
16 K Agarwal Banglore PC01
64
c) To display CustomerName, City, ItemName and Price of those items whose price is more than 50000.
d) To increase the Price of all items by 1000 in the table Item.
e) Give output of the following commands:
i) Select Count(Distinct City) From Customer;
ii) Select ItemName, Max(Price)) From Item Group By ItemName;
iii) Select CustomerName, Manufacturer From Item, Customer
Where Item . I_ID = Customer . I_I_D;
iv) Select ItemName, Price * 100 From Item Where Manufacturer = ‘ABC’;
Answers
1) Select * from CUSTOMER where City = ‘Delhi’;
h. ItemName Price * 10
Personal Computer 350000
Laptop 550000
4) Table : Doctor
ID Name Dept Sex Experience
101 John ENT M 12
104 Smith ORTHOPEDIC M 5
107 George CARDIOLOGY M 10
114 Lara SKIN F 3
109 K George MEDICINE F 9
117 Lucy ENT F 3
Table : Salary
ID Basic Allowance Consultation
101 12000 1000 300
104 23000 2300 500
107 32000 4000 500
114 12000 5200 100
109 42000 1700 200
65
a) Display Name of all doctors who are in ‘MEDICINE’ having more than 10 years experience.
b) Display the Salary of all doctors working in ‘ENT’ department, where Salary = Basic + Allowance.
c) Display the minimum Allowance of female doctors.
d) Increase the Basic Salary of the doctors by 10% whose consultation fees is greater than 200.
e) Give output :
i) Select Count(*) from Doctor where sex = ‘F’;
ii) Select Name, Basic From Doctor, Sal Where Dept = ‘ENT’ And Doctor.ID = Salary.ID;
iii) Select Distinct Dept from Doctor where Sex = ‘M’;
iv) Select Sum(Consultation) from Doctor, Sal where Doctor.ID = Salary.ID and Experience >= 10;
Answers
a) Select Name from Doctor where Dept = ‘MEDICINE’ and Experience > 10;
b) Select Basic + Allowance “ Salary “ from Doctor A , Sal B where A . ID = B . ID and Dept = ‘ENT’;
c) Select Min ( Allowance ) from Doctor A, Sal B Where A . ID = B . ID and Sex = ‘F’;
c) Update Sal set Basic = Basic + 0.1 * Basic where Consultation > 200 ;
i. Count( * )
3
5) Table : Voter
a) To display the information of Voters who live in Delhi and having age in between 30 and 50.
b) Create a view “VIP” having information of male Voters who belong to Area “Civil Lines”.
c) Display Name and Age of male Voters whose name starts with ‘A’ in the descending order of there
Age and alphabetical order of their Name.
d) Display average Age of the male Voters of each city.
66
e) Assign the value of age as 18 to those Voters whose age is NULL.
f) Insert a new row in the table Voter with following values ( 108 , ‘Neha’ , ‘Old City’ , ‘Bareilly’ , ‘F’ ,
36).
Answers
a) Select * from Voter where City = ‘Delhi’ and Age Between 30 and 50;
b) Create View VIP as Select * from Voter where Area = ‘Civil Lines’ and Sex = ‘M’;
c) Select Name , Age from Voter where Sex = ‘F’ and Name Like ‘A%’ Order By Age Desc, Name ;
d) Select Avg ( Age ) from Voter Group By City Having Sex = ‘M’ ;
f) Insert Into Voter Values ( 108 , ‘Neha’ , ‘Old City’ , ‘Bareilly’ , ‘F’ , 36);
Integrating MySQL with Python to write data in a table student (id, name, marks)
import mysql.connector as ms
conobj = ms.connect(host = “localhost”, user = “root”, passwd = “
” , database = “test”)
if conobj.is_connected() == False:
print(“Connection of MySQL database failed”)
cursor = conob.cursor( )
st = “insert into student(id, name, marks) values(501, ‘Sumit’, 78)”
67
cursor.execute(st)
conobj.commit( )
data = conobj.fetchall( )
for i in data :
print( i )
conobj.close( )
Integrating MySQL with Python to display data from a table student who are having marks
above 90.
import mysql.connector as ms
conobj = ms.connect(host = “localhost”, user = “root”, passwd = “
” , database = “test”)
if conobj.is_connected() == False:
print(“Connection of MySQL database failed”)
cursor = conob.cursor( )
st = “insert into student(id, name, marks) values(501, ‘Sumit’, 78)”
cursor.execute(st)
conobj.commit( )
data = conobj.fetchall( )
for i in data :
print( i )
conobj.close( )
Creating URL Confs : The process of linking URLs and displaying actual templates is called
as URL routing.
Open urls.py file for defining URL configurations
Import views .py file of the Apps as : from student import views
Define the path as : path ( ‘first/’ , views.abc )
68
from django.contrib import admin
from django.urls import views
from student import views
urlpatterns = [
path( ‘admin/’ , admin.site.urls ),
path ( ‘first/’ , views.abc ),
]
Write a view function “show” that can process a GET request and display “hello.html” as
template.
Django based web server to parse a user request (POST), and write it to a CSV file.
A view function “inputdata” that can process a POST request and write POST data in a CSV
file “data.csv”. The data contains the records of students in a Python dictionary.
69