0% found this document useful (0 votes)
5 views76 pages

XII Record 2023 2024

This document is a record file for the Computer Science subject (083) for class XII at Smt. Narbada Devi J. Agarwal Vivekananda Vidyalaya for the academic year 2023-2024. It includes a bonafide certificate, an index of Python programs, and detailed descriptions of various programming tasks related to functions, file manipulation, and SQL commands. The document serves as a practical file for students preparing for their All India Senior Secondary Practical Examination.

Uploaded by

24f2005074
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views76 pages

XII Record 2023 2024

This document is a record file for the Computer Science subject (083) for class XII at Smt. Narbada Devi J. Agarwal Vivekananda Vidyalaya for the academic year 2023-2024. It includes a bonafide certificate, an index of Python programs, and detailed descriptions of various programming tasks related to functions, file manipulation, and SQL commands. The document serves as a practical file for students preparing for their All India Senior Secondary Practical Examination.

Uploaded by

24f2005074
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76



Smt. Narbada Devi J. Agarwal Vivekananda


Vidyalaya Sr. Sec. School
(A Unit of Vivekananda Educational Society (Regd))
Mahakavi Bharathi Nagar, Vyasarpadi,
Chennai – 600 039

RECORD FILE – 2023-2024

BOARD EXAM ROLL NO : _______________________

NAME : ________________________________

STANDARD : XII

SECTION :

SUBJECT : COMPUTER SCIENCE (083)

1
BONAFIDE CERTIFICATE

Certified to be the Bonafide Practical file of work done by

__________________________ of class XII in Smt. Narbada

Devi J.Agarwal Vivekananda Vidyalaya Sr. Sec.

School,Vyasarpadi,Chennai – 39 during the year 2023 – 2024.

Date : Subject Teacher Principal

Submitted for All India Senior Secondary Practical Examination

held in Computer Science (083) at Smt. Narbada Devi J.Agarwal

Vivekananda Vidyalaya Sr. Sec. School, Vyasarpadi, Chennai – 39.

Date : External Examiner

School Seal

2
Python Program File – 2023- 2024
Subject : Computer Science (083) Std : XII
Index
Program Teacher
Program Title Page No.
No. Signature
1 Display terms of series using functions

2 To calculate and return the area of shapes

3 String operations using function

4 List operations using function


Function to find Simple Interest using default
5
arguments
6 Simulate dice board using random

7 Text file manipulation

8 Area of 2D shapes using Module

9 Text file statistics

10 Binary file – add and search

11 Binary file – delete and update

12 CSV file – add and display

13 CSV file – insert and search

14 File pointer – seek and tell

15 Store and retrieve in dictionary


16 Stack as a list

17 Interface of python with an SQL database: create


table and desc commands

3
Program Teacher
Program Title Page No.
No. Signature
18 Interface of python with an SQL database: insert
and select commands
19 Interface of python with an SQL database: alter,
update and select commands
20 Interface of python with an SQL database: max(),
upper() functions
SQL COMMANDS

6 SQL – SET 1 (Tables Teacher and Posting)

7 SQL – SET 2 (Tables Trainer and Course)

8 SQL – SET 3 (Tables Account and Transact)

9 SQL – SET 4 (Tables STUDENTS and SPORTS)

10 SQL – SET 5 (Tables DANCE and MUSIC)

4
List of Programs for Term 1 : Computer Science 2012-22

1. Write a menu driven Python code to display n terms of following series using
functions
• 8, 7, 11, 12, 14, 17, 17, 22, ?
• 3, 12, 27, 48, 75, 108, ?

2. Write a menu driven Python program to calculate and return the values of
• Area of triangle
• Area of a circle
• Area of regular polygon

3. Write a menu driven program in Python using user defined functions to take a
string as input and
• Check if it is palindrome
• Count number of occurrences of a given character
• Get an index from user and replace the character at that index with user given value.

4. Write a menu driven program in Python using user defined functions that take a list as
parameter and return
• maximum
• minimum
• sum of the elements

5. Write a menu driven program in Python using user defined functions with keyword
arguments and default values to find
 Simple Interest
 Simple Interest for principal amount of 2000
 Simple Interest for principal amount of 2000 and 5% rate of Interest
 Simple Interest for principal amount of 2000, 5% rate of Interest and 3 years

6. Write a menu driven program in Python using user defined functions to simulate dice board
Game based on random module
 Rules of the Game
 Start Game
 Exit

7. Write a menu driven program in Python to remove all the lines that contain the
character `a' in a file and write it to another file. Menu options are
 Original content of poem.txt
 New content of poem.txt containing lines without character 'a'
 Content in new.txt containing lines with character 'a'
 Exit

8. Write module in Python having user defined functions to perform :


 Area of a square
 Area of a rectangle
 Area of a circle

5
 Area of a triangle

Import the module and invoke the functions.

9. Write a menu driven program in Python using function to a read a text file and •
Count number of characters
• Count number of words
• Count number of vowels
• Count number of lines
• Count number of digits
• Count number of special characters
10. Write a menu driven program in Python using Pickle library andCreate a binary file with
following structure
◦ Admission number
◦ Student name
◦ Age
• Display the contents of the binary file
• Display the student whose age is above user given value
• Search a student by admission number given by user
11. Write a menu driven program in Python using Pickle library and • Create binary file with
following structure
◦ Travelid
◦ From
◦ To
• Append data to the file
• Delete a record based on travelid
• Update a record based on travelid
12. Write a menu driven program in Python to create a CSV file with following data
• Roll no
• Name of student
• Mark in Sub1
• Mark in sub2
• Mark in sub3
• Mark in sub4
• Mark in sub5
Perform following operations on the CSV file after reading it.
• Calculate total and percentage for each student.
• Display the name of student if in any subject marks are greater than 80%
(Assume marks are out of 100)
13. Write a menu driven program in Python to create a CSV file with following data
• Use name
• password
Perform following operations on the CSV file after reading it.
 Add user
 Show user
14. Write a menu driven program in Python to illustrate the file pointer position for
different reference point i.e. from beginning, current and end of the file.
15.Write a menu driven program in python to store state and capital in a dictionary and
 Show details
 Search by State
6
 Search by capital
 Add state/capital

16. Write a menu driven Python code to perform the following functions in the list of
books(Bookno, Book name, Price) stored as a stack :
 Push
 Pop
 Peek
 Display

17. Write a menu driven Python code with SQL connectivity to execute the following
queries:
 Create table store :
Attribute Datatype / constraint
Storeid char(5) Primary Key
Name varchar(20)
Location varchar(20)
City varchar(15)
NoofEmp int(11)
Dateofopen date
Sales int(11)

 Display structure

18. Write a menu driven Python code with SQL connectivity to execute the following
queries:
 Insert Records
Id Name Location City No.of Emp Open Date Sales
1 Reliance MKB Nagar Chennai 15 2018-10-10 50000
2 Bata Mount Road Chennai 20 2019-01-01 70000

 Display records

19. Write a menu driven Python code with SQL connectivity to execute the following
queries:
 Alter table – To add column Discount
 Update table – To update discount as 10% of Sales
 Display records

20. Write a menu driven Python code with SQL connectivity to execute the following
queries:
 Max() - To display store with maximum sales
 Upper() – To display store name in uppercase

7
# PROGRAM 1 – Print Series using Functions

def series1(n):
init1 = 8
init2 = 7
print(init1)
print(init2)
for i in range(3,n+1):
if(i%2==1):
init1 = init1 + 3
print(init1)
else:
init2 = init2 + 5
print(init2)
def series2(n):
mul = 1
term = 0
for i in range(n):
term = term + 3 * mul
mul = mul + 2
print(term)
while(1):
print("\n Menu")
print("1. Series 1 : 8, 7, 11, 12, 14, 17, 17, 22, ?")
print("2. Series 2 : 3, 12, 27, 48, 75, 108, ?")
print("3. Exit")
ch = int(input("Enter your choice:"))
if(ch==1):
n = int(input("Enter the number of terms (greater than
2) :"))
series1(n)
elif(ch==2):
n = int(input("Enter the number of terms :"))
series2(n)

elif(ch==3):
break
else:
print("Wrong Choice")

8
OUTPUT :

Menu
1. Series 1 : 8, 7, 11, 12, 14, 17, 17, 22, ?
2. Series 2 : 3, 12, 27, 48, 75, 108, ?
3. Exit
Enter your choice:1
Enter the number of terms (greater than 2) :7
8
7
11
12
14
17
17

Menu
1. Series 1 : 8, 7, 11, 12, 14, 17, 17, 22, ?
2. Series 2 : 3, 12, 27, 48, 75, 108, ?
3. Exit
Enter your choice:2
Enter the number of terms :7
3
12
27
48
75
108
147

Menu
1. Series 1 : 8, 7, 11, 12, 14, 17, 17, 22, ?
2. Series 2 : 3, 12, 27, 48, 75, 108, ?
3. Exit
Enter your choice:3

9
# PROGRAM 2 : FUNCTIONS WITH AREA

import math

def tarea(b,h):
a = 0.5 * b * h
return a

def carea(r):
a = math.pi * r *r
return a

def rarea(n,s):
a = (s * s * n) / ( 4 * math.tan(math.pi/n))
return a

while(1):
print("\n Menu")
print("1. Area of Triangle")
print("2. Area of Circle")
print("3. Area of Regular polygon")
print("4. Exit")
ch = int(input("Enter your choice:"))
if(ch==1):
b = float(input("Enter the base of triangle : "))
h = float(input("Enter the height of triangle : "))
print("The area of triangle : ",tarea(b,h))
elif(ch==2):
r = float(input("Enter the radius of circle :"))
print("The area of circle :",carea(r))
elif (ch==3):
n= int(input("Enter the number of sides"))
s = float(input("Enter the dimension of side"))
print("The area of the polygon :",rarea(n,s))
elif(ch==4):
break
else:
print("Wrong Choice")

10
OUTPUT :

Menu
1. Area of Triangle
2. Area of Circle
3. Area of Regular polygon
4. Exit
Enter your choice:1
Enter the base of triangle : 14
Enter the height of triangle : 7
The area of triangle : 49.0

Menu
1. Area of Triangle
2. Area of Circle
3. Area of Regular polygon
4. Exit
Enter your choice:2
Enter the radius of circle :40
The area of circle : 5026.548245743669

Menu
1. Area of Triangle
2. Area of Circle
3. Area of Regular polygon
4. Exit
Enter your choice:3
Enter the number of sides5
Enter the dimension of side10
The area of the polygon : 16.128052284937144

Menu
1. Area of Triangle
2. Area of Circle
3. Area of Regular polygon
4. Exit
Enter your choice:4

11
# PROGRAM 3 : FUNCTION WITH STRING

import math

def palindrome(s):
rev = s[::-1]
if(rev == s):
print("The string is palindrome")
else:
print("The string is not a palindrome")

def countc(s,c):
c = s.count(c)
return c

def replacec(s,i):
nc = input("Enter the new character :")
if(len(nc)==1):
ns = s.replace(i,nc)
print("The string after replacement is : ",ns)
else:
print("Error : you have enter only one character")

while(1):
print("\n Menu")
print("1. Palindrome")
print("2. Number of Occurence")
print("3. Replace character")
print("4. Exit")
ch = int(input("Enter your choice:"))
if(ch==1):
s = input("Enter the string :")
palindrome(s)
elif(ch==2):
s = input("Enter the string :")
c = input("Enter a character :")
if(len(c)==1):
print("The character ",c," is in ",s, ",",
countc(s,c), " times")
else:
print("Enter only one character")

elif (ch==3):
s = input("Enter the string :")
i= input("Enter the character to be replaced:")
replacec(s,i)

elif(ch==4):
break
else:
print("Wrong Choice")

12
OUTPUT :

Menu
1. Palindrome
2. Number of Occurence
3. Replace character
4. Exit
Enter your choice:1
Enter the string :MALAYALAM
The string is palindrome

Menu
1. Palindrome
2. Number of Occurence
3. Replace character
4. Exit
Enter your choice:2
Enter the string :ALL THE BEST
Enter a character :T
The character T is in ALL THE BEST , 2 times

Menu
1. Palindrome
2. Number of Occurence
3. Replace character
4. Exit
Enter your choice:3
Enter the string :Practice makes the man perfect
Enter the character to be replaced:e
Enter the new character :*
The string after replacement is : Practic* mak*s th* man p*rf*ct

Menu
1. Palindrome
2. Number of Occurence
3. Replace character
4. Exit
Enter your choice:4

13
# PROGRAM 4 : Functions based on List

def maximum(l):
m = l[0]
for i in range(len(l)):
if(l[i]>m):
m=l[i]
return m

def minimum(l):
m = l[0]
for i in range(len(l)):
if(l[i]<m):
m=l[i]
return m

def suml(l):
s = 0
for i in range(len(l)):
s = s + l[i]
return s

while(1):
print("\n Menu")
print("1. Maximum of list")
print("2. Minimum of list")
print("3. Sum of list")
print("4. Exit")
ch = int(input("Enter your choice:"))
if(ch==1):
l = list(map(int,input("\nEnter the numbers :
").strip().split()))
m = maximum(l)
print("Maximum of given list elements is :",m)
elif(ch==2):
l = list(map(int,input("\nEnter the numbers :
").strip().split()))
m = minimum(l)
print("Minimum of given list elements is :",m)
elif (ch==3):
l = list(map(int,input("\nEnter the numbers :
").strip().split()))
s = suml(l)
print("Sum of given list elements is :",s)
elif(ch==4):
break
else:
print("Wrong Choice")

14
OUTPUT :

Menu
1. Maximum of list
2. Minimum of list
3. Sum of list
4. Exit
Enter your choice:1

Enter the numbers : 1 2 22 56 23 8 90 123 87


Maximum of given list elements is : 123

Menu
1. Maximum of list
2. Minimum of list
3. Sum of list
4. Exit
Enter your choice:2

Enter the numbers : 8 5 3 2 5 8 1


Minimum of given list elements is : 1

Menu
1. Maximum of list
2. Minimum of list
3. Sum of list
4. Exit
Enter your choice:3

Enter the numbers : 2 3 2 5 6 2 4


Sum of given list elements is : 24

Menu
1. Maximum of list
2. Minimum of list
3. Sum of list
4. Exit
Enter your choice:4

15
# PROGRAM 5 : FUNCTION WITH KEYWORD ARGUMENTS AND DEFAULT VALUES

def simpleinterest(prin=2000,rate=5,time=3):
si=(prin*rate*time)/100;
print("Simple Interest of the principal ",prin," Rate of Interest
",rate," Time period ",time," is : ",si)

while (1):
print("\nMenu")
print("1. Simple Interest")
print("2. Simple Interest for principal amount of 2000")
print("3. Simple Interest for principal amount of 2000 and 5%
rate of Interest")
print("4. Simple Interest for principal amount of 2000, 5% rate
of Interest and 3 years")
print("5. Exit")
ch=int(input("Enter your Choice"))
if ch==1:
p=int(input("Enter Principal Amount :"))
r=int(input("Enter Rate of Interest :"))
t=int(input("Enter Time Period :"))
simpleinterest(p,r,t)
elif ch==2:
r=int(input("Enter Rate of Interest :"))
t=int(input("Enter Time Period :"))
simpleinterest(rate=r,time=t)
elif ch==3:
t=int(input("Enter Time Period :"))
simpleinterest(time=t)
elif ch==4:
simpleinterest()
else :
break

16
OUTPUT :

Menu
1. Simple Interest
2. Simple Interest for principal amount of 2000
3. Simple Interest for principal amount of 2000 and 5% rate of
Interest
4. Simple Interest for principal amount of 2000, 5% rate of Interest
and 3 years
5. Exit
Enter your Choice1
Enter Principal Amount :4000
Enter Rate of Interest :5
Enter Time Period :6
Simple Interest of the principal 4000 Rate of Interest 5 Time
period 6 is : 1200.0

Menu
1. Simple Interest
2. Simple Interest for principal amount of 2000
3. Simple Interest for principal amount of 2000 and 5% rate of
Interest
4. Simple Interest for principal amount of 2000, 5% rate of Interest
and 3 years
5. Exit
Enter your Choice2
Enter Rate of Interest :5
Enter Time Period :6
Simple Interest of the principal 2000 Rate of Interest 5 Time
period 6 is : 600.0

Menu
1. Simple Interest
2. Simple Interest for principal amount of 2000
3. Simple Interest for principal amount of 2000 and 5% rate of
Interest
4. Simple Interest for principal amount of 2000, 5% rate of Interest
and 3 years
5. Exit
Enter your Choice3
Enter Time Period :5
Simple Interest of the principal 2000 Rate of Interest 5 Time
period 5 is : 500.0

Menu
1. Simple Interest
2. Simple Interest for principal amount of 2000
3. Simple Interest for principal amount of 2000 and 5% rate of
Interest
4. Simple Interest for principal amount of 2000, 5% rate of Interest
and 3 years
5. Exit
Enter your Choice4
17
Simple Interest of the principal 2000 Rate of Interest 5 Time
period 3 is : 300.0

Menu
1. Simple Interest
2. Simple Interest for principal amount of 2000
3. Simple Interest for principal amount of 2000 and 5% rate of
Interest
4. Simple Interest for principal amount of 2000, 5% rate of Interest
and 3 years
5. Exit
Enter your Choice5

18
#Program 6 : Menu based Dice board Game based on random

import random

def roll(player,score):
num=random.randint(1,6)
if (score+num <= 100):
score=score+num
print(player, " rolled ", num," now score is ",score)
elif (score+num >100):
print(player, " you have to get the exact number to reach the
end")
return score

def play():
score1=0
score2=0
player1=input("Enter name of player 1 : ")
player2=input("Enter name of player 2 : ")
while (score1<100 and score2<100):
score1=roll(player1,score1)
if not score1==100:
score2=roll(player2,score2)
if score1==100:
print(player1, " IS THE WINNER")
elif score2==100:
print(player2, " IS THE WINNER")
def rules():
print('''
About of the Game
=============
This is a number board game from 1 to 100.
2 players can play at a time. The player who
reaches 100 first is declared as the winner.
Number on the dice is system generated''')

while True:
print('''
1. Rules of the Game
2. Start Game
3. Exit
Enter your Choice :''',end='')
ch=int(input())
if ch==1:
rules()
elif ch==2:
play()
elif ch==3 :
break
else:
print("Wrong choice")

19
OUTPUT :

1. Rules of the Game


2. Start Game
3. Exit
Enter your Choice :1

About of the Game


=============
This is a number board game from 1 to 100.
2 players can play at a time. The player who
reaches 100 first is declared as the winner.
Number on the dice is system generated

1. Rules of the Game


2. Start Game
3. Exit
Enter your Choice :2
Enter name of player 1 : Vivek
Enter name of player 2 : Ram
Vivek rolled 1 now score is 1
Ram rolled 6 now score is 6
Vivek rolled 3 now score is 4
Ram rolled 1 now score is 7
Vivek rolled 2 now score is 6
Ram rolled 6 now score is 13
Vivek rolled 2 now score is 8
Ram rolled 1 now score is 14
Vivek rolled 4 now score is 12
Ram rolled 2 now score is 16
Vivek rolled 4 now score is 16
Ram rolled 5 now score is 21
Vivek rolled 3 now score is 19
Ram rolled 1 now score is 22
Vivek rolled 3 now score is 22
Ram rolled 6 now score is 28
Vivek rolled 5 now score is 27
Ram rolled 2 now score is 30
Vivek rolled 1 now score is 28
Ram rolled 3 now score is 33
Vivek rolled 1 now score is 29
Ram rolled 5 now score is 38
Vivek rolled 3 now score is 32
Ram rolled 5 now score is 43
Vivek rolled 5 now score is 37
Ram rolled 6 now score is 49
Vivek rolled 3 now score is 40
Ram rolled 3 now score is 52
Vivek rolled 5 now score is 45
Ram rolled 5 now score is 57
Vivek rolled 2 now score is 47
Ram rolled 4 now score is 61
Vivek rolled 4 now score is 51
Ram rolled 2 now score is 63
20
Vivek rolled 4 now score is 55
Ram rolled 5 now score is 68
Vivek rolled 5 now score is 60
Ram rolled 6 now score is 74
Vivek rolled 2 now score is 62
Ram rolled 6 now score is 80
Vivek rolled 2 now score is 64
Ram rolled 5 now score is 85
Vivek rolled 5 now score is 69
Ram rolled 1 now score is 86
Vivek rolled 1 now score is 70
Ram rolled 4 now score is 90
Vivek rolled 5 now score is 75
Ram rolled 4 now score is 94
Vivek rolled 6 now score is 81
Ram rolled 3 now score is 97
Vivek rolled 3 now score is 84
Ram rolled 1 now score is 98
Vivek rolled 6 now score is 90
Ram you have to get the exact number to reach the end
Vivek rolled 4 now score is 94
Ram rolled 1 now score is 99
Vivek rolled 1 now score is 95
Ram you have to get the exact number to reach the end
Vivek rolled 2 now score is 97
Ram you have to get the exact number to reach the end
Vivek you have to get the exact number to reach the end
Ram rolled 1 now score is 100
Ram IS THE WINNER

1. Rules of the Game


2. Start Game
3. Exit
Enter your Choice :3

21
#Program 7 : Text file handling - reading and writing
#Remove all the lines that contain the character `a' in a file and
write it to another file.

import os

def writenew():
try:
file1=open("poem.txt",'r')
except FileNotFoundError:
print("File does not exist")
exit()
file2=open("new.txt",'w')
file3=open("temp.txt",'w')
line=' '
while True:
line=file1.readline()
if not line:
break
if not 'a' in line:
file3.write(line)
else :
file2.write(line)
file1.close()
file2.close()
file3.close()
os.remove("poem.txt")
os.rename("temp.txt","poem.txt")

def readfile(fname):
try:
file1=open(fname,'r')
except FileNotFoundError:
print("File does not exist")
exit()
l=file1.read()
print(l)
file1.close()

while True:
print('''
Menu
1. Original content of poem.txt
2. New content of poem.txt containing lines without character 'a'
3. Content in new.txt containing lines with character 'a'
4. Exit
Enter the options in the order of 1 to 4 : ''',end=' ')
ch=int(input())
if ch==1:
readfile("poem.txt")
elif ch==2:
writenew()
readfile("poem.txt")
elif ch==3:
22
readfile("new.txt")
elif ch==4:
break
else :
print("Wrong Choice")

23
OUTPUT :

Menu
1.Original content of poem.txt
2.New content of poem.txt containing lines without character 'a'
3.Content in new.txt containing lines with character 'a'
4.Exit
Enter the options in the order of 1 to 4 :1
Stopping by Woods on a Snowy Evening
The woods are lovely, dark, and deep,
But I have promises to keep,
and miles to go
before I sleep,
and miles to go
before I sleep
by Robert Frost

Menu
1.Original content of poem.txt
2.New content of poem.txt containing lines without character 'a'
3.Content in new.txt containing lines with character 'a'
4.Exit
Enter the options in the order of 1 to 4 : 2
before I sleep,
before I sleep
by Robert Frost

Menu
1.Original content of poem.txt
2.New content of poem.txt containing lines without character 'a'
3.Content in new.txt containing lines with character 'a'
4.Exit
Enter the options in the order of 1 to 4 : 3
Stopping by Woods on a Snowy Evening
The woods are lovely, dark, and deep,
But I have promises to keep,
and miles to go
and miles to go

Menu
1. Original content of poem.txt
2. New content of poem.txt containing lines without character 'a'
3. Content in new.txt containing lines with character 'a'
4. Exit
Enter the options in the order of 1 to 4 : 4

24
#Program 8 : Python Module for finding the area of 2D shapes

'''Module to find the area of 2D shapes'''

def sarea():
'''Function to find the area of a square'''
s=int(input("Enter the side of the square :"))
print("Area of the Square:",s*s)

def rarea():
'''Function to find the area of a rectangle'''
l=int(input("Enter the length of the rectangle :"))
b=int(input("Enter the breadth of the rectangle :"))
print("Area of the rectangle :",l*b)

def carea():
'''Function to find the area of a circle'''
r=int(input("Enter the radius of the circle :"))
print("Area of the Circle :",3.14*r**2)

def tarea():
'''Function to find the area of a triangle'''
b=int(input("Enter the base of the triangle :"))
h=int(input("Enter the height of the triangle :"))
print("Area of the triangle :",0.5*b*h)

25
Output :

>>> import area


>>> help(area)
Help on module area:

NAME
area - Module to find the area of 2D shapes

FUNCTIONS
carea()
Function to find the area of a circle

rarea()
Function to find the area of a rectangle

sarea()
Function to find the area of a square

tarea()
Function to find the area of a triangle

FILE
c:\users\staff\appdata\local\programs\python\python36-32\area.py

>>> carea()
Enter the radius of the circle :7
Area of the Circle : 153.86
>>> sarea()
Enter the side of the square :5
Area of the Square: 25
>>> rarea()
Enter the length of the rectangle :5
Enter the breadth of the rectangle :9
Area of the rectangle : 45
>>> tarea()
Enter the base of the triangle :5
Enter the height of the triangle :10
Area of the triangle : 25.0

26
# PROGRAM 9 - Text File Statistics

def character(file):
str=file.read()
print("The number of characters are :",len(str))

def words(file):
str=file.read()
print("The number of words are :",len(str.split()))

def vowels(file):
str=file.read()
count=0
for a in str:
if a in "aeiouAEIOU":
count=count+1
print("The number of vowels are:",count)

def lines(file):
str=file.read()
print("The number of lines are:",str.count('\n'))

def digits(file):
str=file.read()
count=0
for a in str:
if a in "0123456789":
count=count+1
print("The number of digits are :",count)

def spcharacter(file):
str=file.read()
count=0
for a in str:
if not a.isalnum():
count=count+1
print("The number of special characters are :",count)

file = open("read.txt","r")
while(1):
print('''\n menu
1. Count number of characters
2. Count number of words
3. Count number of vowels
4. Count number of lines
5. Count number of digits
6. Count number of special characters
7. Exit''')
ch=int(input('enter choice'))
if (ch==1):
file.seek(0,0)
character(file)
elif (ch==2):
file.seek(0,0)
27
words(file)
elif (ch==3):
file.seek(0,0)
vowels(file)
elif (ch==4):
file.seek(0,0)
lines(file)
elif (ch==5):
file.seek(0,0)
digits(file)
elif (ch==6):
file.seek(0,0)
spcharacter(file)
elif (ch==7):
break
else:
print('invalid input')
file.close()

28
Output :

Menu
1. Count number of characters
2. Count number of words
3. Count number of vowels
4. Count number of lines
5. Count number of digits
6. Count number of special characters
7. Exit
enter choice1
The number of characters are : 50

Menu
1. Count number of characters
2. Count number of words
3. Count number of vowels
4. Count number of lines
5. Count number of digits
6. Count number of special characters
7. Exit
enter choice2
The number of words are : 10

Menu
1. Count number of characters
2. Count number of words
3. Count number of vowels
4. Count number of lines
5. Count number of digits
6. Count number of special characters
7. Exit
enter choice3
The number of vowels are: 13

Menu
1. Count number of characters
2. Count number of words
3. Count number of vowels
4. Count number of lines
5. Count number of digits
6. Count number of special characters
7. Exit
enter choice4
The number of lines are: 2

Menu
1. Count number of characters
2. Count number of words
3. Count number of vowels
4. Count number of lines
5. Count number of digits
6. Count number of special characters

29
7. Exit
enter choice5
The number of digits are : 6

Menu
1. Count number of characters
2. Count number of words
3. Count number of vowels
4. Count number of lines
5. Count number of digits
6. Count number of special characters
7. Exit
enter choice6
The number of special characters are : 14

Menu
1. Count number of characters
2. Count number of words
3. Count number of vowels
4. Count number of lines
5. Count number of digits
6. Count number of special characters
7. Exit
enter choice7

30
# PROGRAM 10 : Binary file handling - read, write and search

import pickle

def writefile(file):
admno = int(input("Enter the admission number :"))
name = input("Enter the name of student :")
age = int(input("Enter the age of student "))
data = admno,name,age
pickle.dump(data,file)

def readfile(file):

while(1):
try:
data = pickle.load(file)
print(data)
except EOFError :
return

def above(file):
cutoff = int(input("Enter the cut off age :"))

while(1):
try:
data = pickle.load(file)
if(data[2]>=cutoff):
print(data)
except EOFError :
return
def search(file):
admno = int(input("Enter the admission number :"))
flag = 0
while(1):
try:
data = pickle.load(file)
if(data[0]==admno):
print(data)
flag = 1
return flag
except EOFError :
return flag

file = open("student.dat","ab+")
while(1):
print('''
Menu
1. Write binary file
2. Read binary file
3. Above given age
4. Search by admission number
5. Exit''')
ch=int(input('Enter choice : '))
if (ch==1):
31
file.seek(0,0)
writefile(file)
elif (ch==2):
file.seek(0,0)
readfile(file)
elif (ch==3):
file.seek(0,0)
above(file)
elif (ch==4):
file.seek(0,0)
res = search(file)
if(res == 0):
print("Record not found")
elif (ch==5):
file.close()
break
else:
print('invalid input')

32
OUTPUT :

Menu
1. Write binary file
2. Read binary file
3. Above given age
4. Search by admission number
5. Exit
Enter choice : 1
Enter the admission number :1
Enter the name of student :Anusuya
Enter the age of student 16

Menu
1. Write binary file
2. Read binary file
3. Above given age
4. Search by admission number
5. Exit
Enter choice : 1
Enter the admission number :2
Enter the name of student :Bhuvanesh
Enter the age of student 17

Menu
1. Write binary file
2. Read binary file
3. Above given age
4. Search by admission number
5. Exit
Enter choice : 2
(1, 'Anusuya', 16)
(2, 'Bhuvanesh', 17)

Menu
1. Write binary file
2. Read binary file
3. Above given age
4. Search by admission number
5. Exit
Enter choice : 3
Enter the cut off age :16
(1, 'Anusuya', 16)
(2, 'Bhuvanesh', 17)

Menu
1. Write binary file
2. Read binary file
3. Above given age
4. Search by admission number
5. Exit
Enter choice : 3
Enter the cut off age :17
33
(2, 'Bhuvanesh', 17)

Menu
1. Write binary file
2. Read binary file
3. Above given age
4. Search by admission number
5. Exit
Enter choice : 4
Enter the admission number :1
(1, 'Anusuya', 16)

Menu
1. Write binary file
2. Read binary file
3. Above given age
4. Search by admission number
5. Exit
Enter choice : 4
Enter the admission number :6
Record not found
Menu
1. Write binary file
2. Read binary file
3. Above given age
4. Search by admission number
5. Exit
Enter choice : 5

34
# PROGRAM 11 - Binary file handling - append, update, delete, display

import pickle
import os

def readfile(file):
while(1):
try:
data = pickle.load(file)
print(data)
except EOFError :
print("End of file")
return

def appendfile(file):
trid = int(input("Enter the travel id :"))
froms = input("Enter the starting point :")
to = input("Enter the destination ")
data = trid,froms,to
pickle.dump(data,file)

def delfile(file):
tid = int(input("Enter the travel id to delete :"))
temp = open("temp.dat","wb")
flag=0
while(1):
try:
data = pickle.load(file)
if(int(data[0])!=tid):
pickle.dump(data,temp)
else :
flag=1
print("Existing data",data)
ch=input("Do you want to delete the
record (y/n)")
if ch!='y':
pickle.dump(data,temp)
print("Updated data",data)
except EOFError :
break
file.close()
temp.close()
if flag==0:
print("Sorry no such travel id")
os.remove("travel.dat")
os.rename("temp.dat","travel.dat")
return

def upfile(file):
tid = int(input("Enter the travel id to update :"))
flag = 0
35
temp = open("temp.dat","wb")
while(1):
try:
data = pickle.load(file)
if(int(data[0])==tid):
print("Existing data",data)
flag = 1
nf = input("Enter the new source: ")
nt = input("Enter the new destination :")
ndata = tid,nf,nt
pickle.dump(ndata,temp)
else:
pickle.dump(data,temp)
except EOFError :
break
file.close()
temp.close()
if flag==0:
print("Sorry no such travel id")
os.remove("travel.dat")
os.rename("temp.dat","travel.dat")
while(1):
print('''
Menu
1. Append data
2. Delete a record
3. Update a record
4. Display the file
5. Exit''')
ch=int(input('enter choice : '))
if (ch==1):
file = open("travel.dat","ab+")
appendfile(file)
file.close()
elif (ch==2):
file = open("travel.dat","ab+")
file.seek(0,0)
delfile(file)

elif (ch==3):
file = open("travel.dat","ab+")
file.seek(0,0)
upfile(file)

elif (ch==4):
file = open("travel.dat","ab+")
file.seek(0,0)
readfile(file)
file.close()
elif (ch==5):
file.close()
break
else:
print('invalid input')
36
OUTPUT :

Menu
1. Append data
2. Delete a record
3. Update a record
4. Display the file
5. Exit
enter choice : 1
Enter the travel id :1
Enter the starting point :Chennai
Enter the destination Bangalore

Menu
1. Append data
2. Delete a record
3. Update a record
4. Display the file
5. Exit
enter choice : 1
Enter the travel id :2
Enter the starting point :Mumbai
Enter the destination Delhi

Menu
1. Append data
2. Delete a record
3. Update a record
4. Display the file
5. Exit
enter choice : 4
(1, 'Chennai', 'Bangalore')
(2, 'Mumbai', 'Delhi')
End of file

Menu
1. Append data
2. Delete a record
3. Update a record
4. Display the file
5. Exit
enter choice : 3
Enter the travel id to update :1
Existing data (1, 'Chennai', 'Bangalore')
Enter the new source: Madurai
Enter the new destination :Coimbatore

Menu
1. Append data
2. Delete a record
3. Update a record
4. Display the file
37
5. Exit
enter choice : 4
(1, 'Madurai', 'Coimbatore')
(2, 'Mumbai', 'Delhi')
End of file

Menu
1. Append data
2. Delete a record
3. Update a record
4. Display the file
5. Exit
enter choice : 2
Enter the travel id to delete :1
Existing data (1, 'Madurai', 'Coimbatore')
Do you want to delete the record (y/n)y

Menu
1. Append data
2. Delete a record
3. Update a record
4. Display the file
5. Exit
enter choice : 4
(2, 'Mumbai', 'Delhi')
End of file

Menu
1. Append data
2. Delete a record
3. Update a record
4. Display the file
5. Exit
enter choice : 5

38
# PROGRAM 12 : CSV file handling - Write and Display function

import csv

def writefile(file):
addrow = csv.writer(file)
r = int(input("Enter the roll no :"))
n = input("Enter the name :")
s1 = int(input("Enter the marks for Subject 1 "))
s2 = int(input("Enter the marks for Subject 2 "))
s3 = int(input("Enter the marks for Subject 3 "))
s4 = int(input("Enter the marks for Subject 4 "))
s5 = int(input("Enter the marks for Subject 5 "))
data = [r,n,s1,s2,s3,s4,s5]
addrow.writerow(data)

def readfile(file):
allrows = csv.reader(file)
for r in allrows:
print("Roll no: ",r[0])
print("Name :",r[1])
total = 0
for i in range(2,7):
print("Subject ",i-1,"marks :",r[i])
total = total + int(r[i])
print ("Total : ",total)
print("Percentage : ", total/5)

def read90(file):
reader = csv.reader(file)
for r in reader:
flag = 0

for i in range(2,7):
if(int(r[i])>90):
flag = 1

if(flag==1):
print("Roll no: ",r[0])
print("Name :",r[1])
for i in range(2,7):
print("Subject",i-1,"marks :",r[i])

while(1):
print('''\nmenu
1. Write to CSV file
2. Display the total and percentage
3. Display students who scored above 90
4. Exit''')
ch=int(input('enter choice'))
if (ch==1):
file = open("student.csv","a+",newline='')
39
writefile(file)
file.close()
elif (ch==2):
file = open("student.csv","r")
file.seek(0,0)
readfile(file)
file.close()
elif (ch==3):
file = open("student.csv","r")
file.seek(0,0)
read90(file)
file.close()
elif (ch==4):
break
else:
print('invalid input')

40
OUTPUT :

menu
1. Write to CSV file
2. Display the total and percentage
3. Display students who scored above 90
4. Exit
enter choice1
Enter the roll no :1
Enter the name :Ajay
Enter the marks for Subject 1 67
Enter the marks for Subject 2 78
Enter the marks for Subject 3 94
Enter the marks for Subject 4 78
Enter the marks for Subject 5 89

menu
1. Write to CSV file
2. Display the total and percentage
3. Display students who scored above 90
4. Exit
enter choice1
Enter the roll no :2
Enter the name :Dinesh
Enter the marks for Subject 1 56
Enter the marks for Subject 2 67
Enter the marks for Subject 3 78
Enter the marks for Subject 4 89
Enter the marks for Subject 5 90

menu
1. Write to CSV file
2. Display the total and percentage
3. Display students who scored above 90
4. Exit
enter choice2
Roll no: 1
Name : Ajay
Subject 1 marks : 67
Subject 2 marks : 78
Subject 3 marks : 94
Subject 4 marks : 78
Subject 5 marks : 89
Total : 406
Percentage : 81.2
Roll no: 2
Name : Dinesh
Subject 1 marks : 56
Subject 2 marks : 67
Subject 3 marks : 78
Subject 4 marks : 89
Subject 5 marks : 90
Total : 380
Percentage : 76.0
41
menu
1. Write to CSV file
2. Display the total and percentage
3. Display students who scored above 90
4. Exit
enter choice3
Roll no: 1
Name : Ajay
Subject 1 marks : 67
Subject 2 marks : 78
Subject 3 marks : 94
Subject 4 marks : 78
Subject 5 marks : 89

menu
1. Write to CSV file
2. Display the total and percentage
3. Display students who scored above 90
4. Exit
enter choice4

42
#Program 13 : CSV file to store and read user name and password
note='''
Note : Passwords must be at least 6 characters in length
and should contain a minimum of 1 lower case letter [a-z],
1 upper case letter [A-Z], 1 numeric character [0-9] and
1 special character'''

import csv

def checkuser(user,type):
with open("user.csv",'r') as f:
obj=csv.reader(f)
for a in obj:
if user==a[0] and type=="check":
print("User already exist. Try again")
return 0
if user==a[0] and type=="show":
print("User name :",a[0],"\nPassword :",a[1])
return
else:
print("User does not exist")
return 1

def checkpass(pw):
uc=False
lc=False
num=False
sp=False
if len(pw)<6:
print("Password to short. Try again")
return 0
for a in pw:
if a.islower():
lc=True
if a.isupper():
uc=True
if a.isdigit():
num=True
if a.isspace():
print("Password should not have space.")
return 0
if not a.isalnum():
sp=True
if lc and uc and num and sp:
return 1
else:
print("Invalid password. Try again")
return 0

def adduser():
with open("user.csv",'a',newline='') as file:
obj=csv.writer(file)
while True:
43
name=input("Enter user name:")
flag=checkuser(name,"check")
if flag==0:
continue
else:
break
print(note)

while True:
password=input("Enter password :")
s=checkpass(password)
if s==0:
continue
else:
print("Valid password")
break
data=[name,password]
obj.writerow(data)
print("User added")

#main
while True:
print('''
User Login
1. Add user
2. Show user
3. Exit
Enter your choice''',end=' ')
choice=int(input())
if choice==1:
adduser()
elif choice==2:
name=input("Enter username:")
checkuser(name,"show")
elif choice==3:
break
else:
print("Invalid choice, Try again")

44
Output :

User Login
1. Add user
2. Show user
3. Exit
Enter your choice 1
Enter user name:raji
User already exist. Try again
Enter user name:abc
User already exist. Try again
Enter user name:poi
User does not exist

Note : Passwords must must be at least 6 characters in length


and should contain a minimum of 1 lower case letter [a-z],
1 upper case letter [A-Z], 1 numeric character [0-9] and
1 special character

Enter password :se287r


Invalid password. Try again

Enter password :Sd134&


Valid password
User added

User Login
1. Add user
2. Show user
3. Exit
Enter your choice 2
Enter username:poi
User name : poi
Password : Sd134&

User Login
1. Add user
2. Show user
3. Exit
Enter your choice 2
Enter username:raji
User name : raji
Password : raji123

User Login
1. Add user
2. Show user
3. Exit
Enter your choice 2
Enter username:abc
User name : abc
Password : ads2378

User Login
45
1. Add user
2. Show user
3. Exit
Enter your choice 2
Enter username:erw
User does not exist

User Login
1. Add user
2. Show user
3. Exit
Enter your choice 3

46
#Program 14 : File pointer movement using seek() and tell()

def display():
f.seek(0,0)
data=f.read().decode('utf-8')
print(data)

def begin(n):
f.seek(n,0)
print("Cursor Position :", f.tell(), "at",
f.read(1).decode('utf-8'))

def current_f(n):
f.seek(n,1)
print("Cursor Position :", f.tell(), "at",
f.read(1).decode('utf-8'))

def current_r(n):
f.seek(-n,1)
print("Cursor Position :", f.tell(), "at",
f.read(1).decode('utf-8'))

def last(n):
f.seek(-n,2)
print("Cursor Position :", f.tell(), "at",
f.read(1).decode('utf-8'))

with open("about.txt",'rb') as f:

while True:

print('''
File pointer movement
1. Display file content
2. Beginning of file
3. Current cursor position forward
4. Current cursor position backward
5. End of File
6. Exit
Enter your choice''',end='')

ch=int(input())

if ch==1:
display()
elif ch==2:
noc=int(input("Enter number of characters:"))
begin(noc)
elif ch==3:
noc=int(input("Enter number of characters:"))
current_f(noc)
elif ch==4:
noc=int(input("Enter number of characters:"))
current_r(noc)
47
elif ch==5:
noc=int(input("Enter number of characters:"))
last(noc)
elif ch==6:
break
else:
print("Invalid choice. Try again")

48
OUTPUT :

File pointer movement


1. Display file content
2. Beginning of file
3. Current cursor position forward
4. Current cursor position backward
5. End of File
6. Exit
Enter your choice1
Python is an interpreted high-level general-purpose programming
language.

File pointer movement


1. Display file content
2. Beginning of file
3. Current cursor position forward
4. Current cursor position backward
5. End of File
6. Exit
Enter your choice2
Enter number of characters:5
Cursor Position : 5 at n

File pointer movement


1. Display file content
2. Beginning of file
3. Current cursor position forward
4. Current cursor position backward
5. End of File
6. Exit
Enter your choice3
Enter number of characters:5
Cursor Position : 11 at n

File pointer movement


1. Display file content
2. Beginning of file
3. Current cursor position forward
4. Current cursor position backward
5. End of File
6. Exit
Enter your choice4
Enter number of characters:5
Cursor Position : 7 at i

File pointer movement


1. Display file content
2. Beginning of file
3. Current cursor position forward
4. Current cursor position backward
5. End of File
6. Exit
Enter your choice5
49
Enter number of characters:12
Cursor Position : 61 at n

File pointer movement


1. Display file content
2. Beginning of file
3. Current cursor position forward
4. Current cursor position backward
5. End of File
6. Exit
Enter your choice6

50
Program 15 : To store state and capital in dictionary and search
based on key and value.
india={
"Karnataka":"Bengaluru",
"Kerala":"Thiruvananthapuram",
"Madhya Pradesh":"Bhopal",
"Maharashtra":"Mumbai",
"Odisha":"Bhubaneswar",
"Punjab":"Chandigarh",
"Rajasthan":"Jaipur",
"Tamil Nadu":"Chennai",
"West Bengal":"Kolkata"}

while True:
print('''
India State and Capital
1. Show all
2. Search by State
3. Search by Capital
4. Add State and Capital
5. Exit
Enter your choice :''',end='')
ch=int(input())
if ch==1:
print('%-15s %-15s'%("State","Capital"))
print('%-15s %-15s'%("=====","======="))
for a in india:
print('%-15s %-15s'%(a,india[a]))
elif ch==2:
state=input("Enter State name:")
for a in india:
if a.upper()==state.upper():
print("State:",a,"Capital:",india[a])
break
else:
print("Invalid state")
elif ch==3:
capital=input("Enter Capital name:")
for a in india:
if india[a].upper()==capital.upper():
print("State:",a,"Capital:",india[a])
break
else:
print("Invalid Capital")
elif ch==4:
s=input("Enter State :")
c=input("Enter Capital :")
india[s]=c
print("State :",s,"Capital :",c, "added to the dictionary")
else:
break

51
OUTPUT:
India State and Capital
1. Show all
2. Search by State
3. Search by Capital
4. Add State and Capital
5. Exit
Enter your choice :1
State Capital
===== =======
Karnataka Bengaluru
Kerala Thiruvananthapuram
Madhya Pradesh Bhopal
Maharashtra Mumbai
Odisha Bhubaneswar
Punjab Chandigarh
Rajasthan Jaipur
Tamil Nadu Chennai
West Bengal Kolkata

India State and Capital


1. Show all
2. Search by State
3. Search by Capital
4. Add State and Capital
5. Exit
Enter your choice :2
Enter State name:odisha
State: Odisha Capital: Bhubaneswar

India State and Capital


1. Show all
2. Search by State
3. Search by Capital
4. Add State and Capital
5. Exit
Enter your choice :3
Enter Capital name:Kolkata
State: West Bengal Capital: Kolkata

India State and Capital


1. Show all
2. Search by State
3. Search by Capital
4. Add State and Capital
5. Exit
Enter your choice :4
Enter State :Telangana
Enter Capital :Hyderabad
State : Telangana Capital : Hyderabad added to the dictionary

India State and Capital


1. Show all
2. Search by State
52
3. Search by Capital
4. Add State and Capital
5. Exit
Enter your choice :1
State Capital
===== =======
Karnataka Bengaluru
Kerala Thiruvananthapuram
Madhya Pradesh Bhopal
Maharashtra Mumbai
Odisha Bhubaneswar
Punjab Chandigarh
Rajasthan Jaipur
Tamil Nadu Chennai
West Bengal Kolkata
Telangana Hyderabad

India State and Capital


1. Show all
2. Search by State
3. Search by Capital
4. Add State and Capital
5. Exit
Enter your choice :5

53
# PROGRAM 16 - Stack as a list

s = []

def push():
b_ID=int(input('enter book no.'))
b_NAME=input('enter book name:')
b_PRICE=float(input('enter price:'))
data=b_ID,b_NAME,b_PRICE
s.append(data)
print("Book added to stack")

def pop():

if len(s)==0:
print('Underflow -Stack is empty')
else:
dn = s.pop()
print("Popped :",dn)
def peek():
if len(s)==0:
print('Stack is empty')
else:
print("Top most element:",s[-1])
def disp():
if len(s)==0:
print('Stack is empty')
else:
for i in range(len(s)-1,-1,-1):
print("Book Id :",s[i][0])
print("Book Name :",s[i][1])
print("Book Price :",s[i][2])
while(1):
print('''
Menu
1. Push
2. Pop
3. Peek
4. Display
5. Exit''')
ch=int(input('enter choice'))
if (ch==1):
push()
elif (ch==2):
pop()
elif(ch==3):
peek()
elif(ch==4):
disp()
elif (ch==5):
break
else:
print('invalid input')

54
Program 16 : Output
Menu
1. Push
2. Pop
3. Peek
4. Display
5. Exit
enter choice1
enter book no.1
enter book name:Alice in Wonderland
enter price:450
Book added to stack

Menu
1. Push
2. Pop
3. Peek
4. Display
5. Exit
enter choice1
enter book no.2
enter book name:Gone with the wind
enter price:450
Book added to stack

Menu
1. Push
2. Pop
3. Peek
4. Display
5. Exit
enter choice1
enter book no.3
enter book name:Pride and Prejudice
enter price:350
Book added to stack

Menu
1. Push
2. Pop
3. Peek
4. Display
5. Exit
enter choice4
Book Id : 3
Book Name : Pride and Prejudice
Book Price : 350.0
Book Id : 2
Book Name : Gone with the wind
Book Price : 450.0
Book Id : 1
Book Name : Alice in Wonderland
Book Price : 450.0

55
Menu
1. Push
2. Pop
3. Peek
4. Display
5. Exit
enter choice2
Popped : (3, 'Pride and Prejudice', 350.0)

Menu
1. Push
2. Pop
3. Peek
4. Display
5. Exit
enter choice3
Top most element: (2, 'Gone with the wind', 450.0)

Menu
1. Push
2. Pop
3. Peek
4. Display
5. Exit
enter choice2
Popped : (2, 'Gone with the wind', 450.0)

Menu
1. Push
2. Pop
3. Peek
4. Display
5. Exit
enter choice2
Popped : (1, 'Alice in Wonderland', 450.0)

Menu
1. Push
2. Pop
3. Peek
4. Display
5. Exit
enter choice3
Stack is empty

Menu
1. Push
2. Pop
3. Peek
4. Display
5. Exit
enter choice4
Stack is empty

56
Menu
1. Push
2. Pop
3. Peek
4. Display
5. Exit
enter choice5

57
#Program 17 - Interface of python with an SQL database:
# create and desc commands
import mysql.connector as sqltor

db=sqltor.connect(user='root',passwd='vivek',database='classroom')
cursor=db.cursor()

def create():
cursor.execute('''CREATE TABLE STORE
(Storeid char(5) Primary Key,
Name varchar(20),
Location varchar(20),
City varchar(15),
NoofEmp int,
Dateofopen date,
Sales int)''')

def dispstruct():
cursor.execute('''describe STORE''')
row = cursor.fetchall()
print("%-12s%-12s%-12s%-12s%-12s%-
12s"%("Column","Datatype","Null","Key","Default","Extra"))
for c in row:
print("%-12s%-12s%-12s%-12s%-12s%-12s"%
(c[0],c[1],c[2],c[3],c[4],c[5]))

while(1):
print('''
Menu
1. Create table
2. Display structure
3. Exit''')
ch=int(input('enter choice'))
if (ch==1):
create()
print("Table Created…")
elif (ch==2):
dispstruct()
elif (ch==3):
break
else:
print('invalid input')
db.close()

58
Program 17 : Output

Menu
1. Create table
2. Display structure
3. Exit
enter choice1
Table Created…

Menu
1. Create table
2. Display structure
3. Exit
enter choice2
Column Datatype Null Key Default Extra
Storeid char(5) NO PRI None
Name varchar(20) YES None
Location varchar(20) YES None
City varchar(15) YES None
NoofEmp int(11) YES None
Dateofopen date YES None
Sales int(11) YES None

Menu
1. Create table
2. Display structure
3. Exit
enter choice3

59
# PROGRAM 18 - Interface of python with an SQL database:
# create, desc, insert and select commands
import mysql.connector as sqltor

db=sqltor.connect(user='root',passwd='vivek',database='classroom')
cursor=db.cursor()

def show():
cursor.execute('''select * from STORE''')
row = cursor.fetchall()
print("%-5s%-12s%-12s%-12s%-12s%-12s%-
10s"%("Id","Name","Location","City","No.of Emp","Open Date","Sales"))
for c in row:
print("%-5s%-12s%-12s%-12s%-12s%-12s%-
10s"%(c[0],c[1],c[2],c[3],c[4],c[5],c[6]))

def insert():
try:
a=input('Enter storeid: ')
b=input('Enter name : ')
c=input('Enter Location :')
d=input('Enter City : ')
e=int(input('Enter NoofEmp : '))
f= input("Enter the date of opening (yyyy-mm-dd):")
g = int(input('Enter sales : '))
cursor.execute('''INSERT INTO STORE VALUES
(%s,%s,%s,%s,%s,%s,%s)''',(a,b,c,d,e,f,g))
db.commit()
except :
print("error")
db.rollback()
return

while(1):
print('''
Menu
1. Insert Records
2. Display records
3. Exit''')
ch=int(input('enter choice'))
if (ch==1):
insert()
elif (ch==2):
show()
elif (ch==3):
break
else:
print('invalid input')
db.close()

60
Program 18 : Output

Menu
1. Insert Records
2. Display records
3. Exit
enter choice1

Enter storeid: 1
Enter name : Reliance
Enter Location :MKB Nagar
Enter City : Chennai
Enter NoofEmp : 15
Enter the date of opening (yyyy-mm-dd):2018-10-10
Enter sales : 50000

Menu
1. Insert Records
2. Display records
3. Exit
enter choice1

Enter storeid: 2
Enter name : Bata
Enter Location :Mount Road
Enter City : Chennai
Enter NoofEmp : 20
Enter the date of opening (yyyy-mm-dd):2019-01-01
Enter sales : 70000

Menu
1. Insert Records
2. Display records
3. Exit
enter choice2

Id Name Location City No.of Emp Open Date Sales


1 Reliance MKB Nagar Chennai 15 2018-10-10 50000
2 Bata Mount Road Chennai 20 2019-01-01 70000

Menu
1. Insert Records
2. Display records
3. Exit
enter choice3

61
# PROGRAM 19 : Interface of python with an SQL database:
# alter, update and select commands
import mysql.connector as sqltor

db=sqltor.connect(user='root',passwd='vivek',database='classroom')
cursor=db.cursor()

def altertab():
try:
cursor.execute('''alter table STORE add discount integer''')
print("Column Discount added")
except:
print("Column already exists")
return

def update():
try:
cursor.execute('''update STORE set discount=discount/10''')
except:
print("Update Error Check if the column exists…")
return
db.commit()
print("Column Discount updated")

def display():
cursor.execute('''select * from STORE''')
row = cursor.fetchall()
print("%-5s%-12s%-12s%-12s%-12s%-7s%-10s%-10s
"%("Id","Name","Location","City","No.of Emp","Open
Date","Sales","Discount"))

for c in row:
print("%-5s%-12s%-12s%-12s%-12s%-12s%-
10s"%(c[0],c[1],c[2],c[3],c[4],c[5],c[6]))

while(1):
print('''
Menu
1. Alter table
2. Update table
3. Display table
4. Exit''')
ch=int(input('enter choice'))
if (ch==1):
altertab()
elif (ch==2):
update()
elif (ch==3):
display()
elif (ch==4):
break
else:
print('invalid input')

62
Program 19 : Output

Menu
1. Alter table
2. Update table
3. Display table
4. Exit
enter choice1
Column Discount added

Menu
1. Alter table
2. Update table
3. Display table
4. Exit
enter choice2
Column Discount updated

Menu
1. Alter table
2. Update table
3. Display table
4. Exit
enter choice3

Id Name Location City No.of Emp Date Sales Discount


1 Reliance MKB Nagar Chennai 15 2018-10-10 50000 None
2 Bata Mount Road Chennai 20 2019-01-01 70000 None

Menu
1. Alter table
2. Update table
3. Display table
4. Exit
enter choice4

63
# PROGRAM 20 - Interface of python with an SQL database: max(),
upper() functions

import mysql.connector as sqltor


db=sqltor.connect(user='root',passwd='vivek',database='classroom')
cursor=db.cursor()

def max_sales():
cursor.execute('''select max(sales) from STORE''')
row = cursor.fetchone()
print("Maximum Sales of Stores:",row[0])

def storename():
cursor.execute('''select upper(name) from STORE''')
row = cursor.fetchall()
print("STORE NAME")
for a in row:
print(a[0])

while(1):
print('''
Menu
1. Maximum Sales
2. Store Name in uppercase
3. Exit''')
ch=int(input('enter choice'))
if (ch==1):
max_sales()
elif (ch==2):
storename()
elif (ch==3):
break
else:
print('invalid input')
db.close()

64
Program 20 : Output

Menu
1. Maximum Sales
2. Store Name in uppercase
3. Exit
enter choice1
Maximum Sales of Stores: 70000

Menu
1. Maximum Sales
2. Store Name in uppercase
3. Exit
enter choice2
STORE NAME
RELIANCE
BATA

Menu
1. Maximum Sales
2. Store Name in uppercase
3. Exit
enter choice3

65
66
SET 1

Consider the following Teacher and Posting. Write SQL commands for the
statements 1 to 5 and give the outputs.

Table : Teacher

+------+----------+------+------------------+--------------+-------+-----+
| t_id | name | age | department | date_of_join | salary|gender|
+------+----------+------+------------------+--------------+-------+-----+
| 1 | Jugal | 34 | Computer Science | 2017-01-10 | 12000| M |
| 2 | Sharmila | 31 | History | 2008-03-24 | 20000| F |
| 3 | Sandeep | 32 | Mathematics | 2016-12-12 | 30000| M |
| 4 | Sangeeta | 35 | History | 2015-07-01 | 40000| F |
| 5 | Rakesh | 42 | Mathematics | 2007-09-05 | 25000| M |
| 6 | Shyam | 50 | History | 2008-06-27 | 30000| M |
| 7 | Shiv Om | 44 | Computer Science | 2017-02-25 | 21000| M |
| 8 | Shalakha | 33 | Mathematics | 2018-07-31 | 20000| F |
+------+----------+------+------------------+--------------+-------+-----+

Table :Posting
+------+------------------+--------+
| p_id | department | place |
+------+------------------+--------+
| 1 | History | Agra |
| 2 | Mathematics | Raipur |
| 3 | Computer Science | Delhi |
+------+------------------+--------+

1. Display Name, age and department of all teachers in alphabetic order of


name.
2. Display details of teacher who have joined in the year 2017
3. Display number of teachers in each department.
4. Display name, department and place of teachers from History and
Mathematics department.
5. Increase the salary by 1000 for teachers in Mathematics department.

67
SET 1 – OUTPUT

mysql> select name,age,department from teacher order by name;


+----------+------+------------------+
| name | age | department |
+----------+------+------------------+
| Jugal | 34 | Computer Science |
| Rakesh | 42 | Mathematics |
| Sandeep | 32 | Mathematics |
| Sangeeta | 35 | History |
| Shalakha | 33 | Mathematics |
| Sharmila | 31 | History |
| Shiv Om | 44 | Computer Science |
| Shyam | 50 | History |
+----------+------+------------------+
8 rows in set (0.00 sec)

mysql> select * from teacher where year(date_of_join)="2017";


+------+---------+------+------------------+--------------+--------+------+
| t_id | name | age | department | date_of_join | salary |gender|
+------+---------+------+------------------+--------------+--------+------+
| 1 | Jugal | 34 | Computer Science | 2017-01-10 | 12000 | M |
| 7 | Shiv Om | 44 | Computer Science | 2017-02-25 | 21000 | M |
+------+---------+------+------------------+--------------+--------+------+
2 rows in set (0.02 sec)

mysql> select department,count(department) from teacher group by


department;
+------------------+-------------------+
| department | count(department) |
+------------------+-------------------+
| Computer Science | 2 |
| History | 3 |
| Mathematics | 3 |
+------------------+-------------------+
3 rows in set (0.03 sec)

mysql> select name,t.department,place from teacher t,posting p where


t.department=p.department and t
.department in ("History","Mathematics");
+----------+-------------+--------+
| name | department | place |
+----------+-------------+--------+
| Sharmila | History | Agra |
| Sandeep | Mathematics | Raipur |
| Sangeeta | History | Agra |
| Rakesh | Mathematics | Raipur |
| Shyam | History | Agra |
| Shalakha | Mathematics | Raipur |
+----------+-------------+--------+
6 rows in set (0.03 sec)

mysql> update teacher set salary=salary+1000 where


department="Mathematics";
Query OK, 3 rows affected (0.08 sec)
Rows matched: 3 Changed: 3 Warnings: 0

68
SET 2

Consider the following Trainer and Course. Write SQL commands for the
statements 1 to 5 and give the outputs.

TABLE : TRAINER
+-----+------------+------------+------------+--------+
| tid | tname | city | hiredate | salary |
+-----+------------+------------+------------+--------+
| 101 | SUNAINA | MUMBAI | 1998-10-15 | 90000 |
| 102 | ANAMIKA | DELHI | 1994-12-24 | 80000 |
| 103 | DEEPTHI | CHANDIGARG | 2001-12-21 | 82000 |
| 104 | MEENAKSHI | DELHI | 2002-12-24 | 78000 |
| 105 | RICHA | MUMBAI | 1996-01-12 | 95000 |
| 106 | MANIPRABHA | CHENNAI | 2001-12-12 | 69000 |
+-----+------------+------------+------------+--------+

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 |
+------+---------+-------+------------+------+

1. Display the Trainer Name, City, Salary and hiredate in descending order
of their Hiredate.

2. To display the TNAME and CITY of Trainer who joined the Institute in the
month of December 2001.

3. To display TNAME, HIREDATE, CNAME, STARTDATE from tables TRAINER and


COURSE of all those courses whose FEES is less than or equal to 10000.

4. To display number of Trainers from each city which has only 1 Trainer.

5. Add a column STATUS varchar(7) to COURSE table with default value


“ACTIVE”.

69
SET 2 – OUTPUT

mysql> SELECT TNAME, CITY,SALARY,HIREDATE FROM TRAINER ORDER BY HIREDATE


DESC;
+------------+------------+--------+------------+
| TNAME | CITY | SALARY | HIREDATE |
+------------+------------+--------+------------+
| MEENAKSHI | DELHI | 78000 | 2002-12-24 |
| DEEPTHI | CHANDIGARG | 82000 | 2001-12-21 |
| MANIPRABHA | CHENNAI | 69000 | 2001-12-12 |
| SUNAINA | MUMBAI | 90000 | 1998-10-15 |
| RICHA | MUMBAI | 95000 | 1996-01-12 |
| ANAMIKA | DELHI | 80000 | 1994-12-24 |
+------------+------------+--------+------------+
6 rows in set (0.00 sec)

mysql> SELECT TNAME,CITY FROM TRAINER WHERE MONTH(HIREDATE)=12 AND


YEAR(HIREDATE)=2001;
+------------+------------+
| TNAME | CITY |
+------------+------------+
| DEEPTHI | CHANDIGARG |
| MANIPRABHA | CHENNAI |
+------------+------------+
2 rows in set (0.02 sec)

mysql> SELECT TNAME,HIREDATE,CNAME,STARTDATE FROM TRAINER T, COURSE C WHERE


C.TID=T.TID AND FEES<10000;
+-----------+------------+-------+------------+
| TNAME | HIREDATE | CNAME | STARTDATE |
+-----------+------------+-------+------------+
| MEENAKSHI | 2002-12-24 | DDTP | 2018-09-15 |
+-----------+------------+-------+------------+
1 row in set (0.03 sec)

mysql> SELECT CITY,COUNT(TID) FROM TRAINER GROUP BY CITY HAVING


COUNT(TID)=1;
+------------+------------+
| CITY | COUNT(TID) |
+------------+------------+
| CHANDIGARG | 1 |
| CHENNAI | 1 |
+------------+------------+
2 rows in set (0.00 sec)

mysql> ALTER TABLE COURSE ADD STATUS VARCHAR(7) DEFAULT "ACTIVE";


Query OK, 6 rows affected (0.42 sec)
Records: 6 Duplicates: 0 Warnings: 0

70
SET 3

Consider the following Account and Transact. Write SQL commands for the
statements 1 to 5 and give the outputs.

TABLE : ACCOUNT
+-----+---------+---------+------------+
| ANO | ANAME | SURNAME | CITY |
+-----+---------+---------+------------+
| 101 | Nirja | Singh | Bangalore |
| 102 | Rohan | Gupta | Chennai |
| 103 | Ali | Reza | Hyderabad |
| 104 | Rishabh | Jain | Chennai |
| 105 | Simran | Kaur | Chandigarh |
+-----+---------+---------+------------+

TABLE : TRANSACT
+------+------+--------+----------+------------+
| TRNO | ANO | AMOUNT | TYPE | DOT |
+------+------+--------+----------+------------+
| T001 | 101 | 2500 | Withdraw | 2017-12-21 |
| T002 | 103 | 3000 | Deposit | 2017-06-01 |
| T003 | 102 | 2000 | Withdraw | 2017-05-12 |
| T004 | 103 | 1000 | Deposit | 2017-10-22 |
| T005 | 101 | 12000 | Deposit | 2017-11-06 |
+------+------+--------+----------+------------+

1. To display details of all transactions of TYPE Deposit from Table


TRANSACT

2. To display details of account holders whose name starts with „R‟ or „S‟.

3. To display the last date of transaction (DOT) from the table TRANSACT
for the Accounts having ANO as 103.

4. To display all ANO, ANAME,AMOUNT and DOT of those persons from tables
ACCOUNT and TRANSACT who have done transactions less than or equal to 3000.

5. To delete the transaction „T005‟

71
SET 3 - OUTPUT

mysql> select * from transact where type="Deposit";


+------+------+--------+---------+------------+
| TRNO | ANO | AMOUNT | TYPE | DOT |
+------+------+--------+---------+------------+
| T002 | 103 | 3000 | Deposit | 2017-06-01 |
| T004 | 103 | 1000 | Deposit | 2017-10-22 |
| T005 | 101 | 12000 | Deposit | 2017-11-06 |
+------+------+--------+---------+------------+
3 rows in set (0.00 sec)

mysql> select * from account where aname like "R%" or aname like "S%";
+-----+---------+---------+------------+
| ANO | ANAME | SURNAME | CITY |
+-----+---------+---------+------------+
| 102 | Rohan | Gupta | Chennai |
| 104 | Rishabh | Jain | Chennai |
| 105 | Simran | Kaur | Chandigarh |
+-----+---------+---------+------------+
3 rows in set (0.00 sec)

mysql> select max(dot) from transact where ano=103;


+------------+
| max(dot) |
+------------+
| 2017-10-22 |
+------------+
1 row in set (0.03 sec)

mysql> select a.ano,aname,dot,amount from account a, transact t where


a.ano=t.ano and amount<=3000;
+-----+-------+------------+--------+
| ano | aname | dot | amount |
+-----+-------+------------+--------+
| 101 | Nirja | 2017-12-21 | 2500 |
| 103 | Ali | 2017-06-01 | 3000 |
| 102 | Rohan | 2017-05-12 | 2000 |
| 103 | Ali | 2017-10-22 | 1000 |
+-----+-------+------------+--------+
4 rows in set (0.00 sec)

mysql> delete from transact where TRNO="T005";


Query OK, 1 row affected (0.06 sec)

72
SET 4

Consider the following STUDENTS and SPORTS. Write SQL commands for the
statements 1 to 5 and give the outputs.

TABLE : STUDENTS
+-------+--------+-------+------+------+---------+---------+
| ADMNO | NAME | CLASS | SEC | RNO | ADDRESS | PHONE |
+-------+--------+-------+------+------+---------+---------+
| 1211 | MEENA | 12 | D | 4 | A-26 | 3245678 |
| 1212 | VANI | 10 | D | 1 | B-25 | 5456789 |
| 1213 | MEENA | 12 | A | 1 | NULL | NULL |
| 1214 | KARISH | 10 | B | 3 | AB-234 | 4567890 |
+-------+--------+-------+------+------+---------+---------+

TABLE: SPORTS
+-------+-------------+--------------+-------+
| ADMNO | GAME | COACHNAME | GRADE |
+-------+-------------+--------------+-------+
| 1215 | CRICKET | MR.RAVI | A |
| 1213 | VOLLEY BALL | MR.AMANDEEP | B |
| 1211 | VOLLEY BALL | MR.GOVARDHAN | A |
| 1212 | BASKET BALL | MR.TEWARI | B |
+-------+-------------+--------------+-------+

1. To display the details of students from section „A‟ and „B‟.

2. To display name and address of those students whose address is available


in students table

3. To display admno,name,coachname,game of all the students who have been


assigned coach.

4. To display distinct game from sports.

5. Delete the table sports along with its values.

73
SET – 4- OUTPUT

mysql> select * from students where sec='a' or sec='b';


+-------+--------+-------+------+------+---------+---------+
| ADMNO | NAME | CLASS | SEC | RNO | ADDRESS | PHONE |
+-------+--------+-------+------+------+---------+---------+
| 1213 | MEENA | 12 | A | 1 | NULL | NULL |
| 1214 | KARISH | 10 | B | 3 | AB-234 | 4567890 |
+-------+--------+-------+------+------+---------+---------+
2 rows in set (0.00 sec)

mysql> select name,address from students where address is not null;


+--------+---------+
| name | address |
+--------+---------+
| MEENA | A-26 |
| VANI | B-25 |
| KARISH | AB-234 |
+--------+---------+
3 rows in set (0.00 sec)

mysql> select admno,name,coachname,game from students s natural join sports


t;
+-------+-------+--------------+-------------+
| admno | name | coachname | game |
+-------+-------+--------------+-------------+
| 1211 | MEENA | MR.GOVARDHAN | VOLLEY BALL |
| 1212 | VANI | MR.TEWARI | BASKET BALL |
| 1213 | MEENA | MR.AMANDEEP | VOLLEY BALL |
+-------+-------+--------------+-------------+
3 rows in set (0.00 sec)

mysql> select distinct(game) from sports;


+-------------+
| game |
+-------------+
| CRICKET |
| VOLLEY BALL |
| BASKET BALL |
+-------------+
3 rows in set (0.00 sec)

mysql> drop table sports;


Query OK, 0 rows affected (0.08 sec)

74
SET 5

Consider the following DANCE and MUSIC. Write SQL commands for the
statements 1 to 5 and give the outputs.

TABLE : DANCE
+------+--------+-------+
| sno | name | class |
+------+--------+-------+
| 1 | Aastha | 7A |
| 2 | Mahira | 6A |
| 3 | Mohit | 7B |
| 4 | Sanjay | 7A |
+------+--------+-------+

TABLE : MUSIC

+------+---------+-------+
| sno | name | class |
+------+---------+-------+
| 1 | Mehak | 8A |
| 2 | Mahira | 6A |
| 3 | Lavanya | 7A |
| 4 | Sanjay | 7A |
| 5 | Abhay | 8A |
+------+---------+-------+

1. To display the union of Dance and Music.

2. To display the intersection of Dance and Music.

3. To display the Cartesian product of Dance and Music.

4. To display current date.

5. To display the day of “01-01-2022” with the heading “2022 begins on”

75
SET – 5- OUTPUT
mysql> select * from music union select * from dance;
+------+---------+-------+
| sno | name | class |
+------+---------+-------+
| 1 | Mehak | 8A |
| 2 | Mahira | 6A |
| 3 | Lavanya | 7A |
| 4 | Sanjay | 7A |
| 5 | Abhay | 8A |
| 1 | Aastha | 7A |
| 3 | Mohit | 7B |
+------+---------+-------+
mysql> select * from music natural join dance;
+------+--------+-------+
| sno | name | class |
+------+--------+-------+
| 2 | Mahira | 6A |
| 4 | Sanjay | 7A |
+------+--------+-------+
mysql> select * from dance,music;
+------+--------+-------+------+---------+-------+
| sno | name | class | sno | name | class |
+------+--------+-------+------+---------+-------+
| 1 | Aastha | 7A | 1 | Mehak | 8A |
| 2 | Mahira | 6A | 1 | Mehak | 8A |
| 3 | Mohit | 7B | 1 | Mehak | 8A |
| 4 | Sanjay | 7A | 1 | Mehak | 8A |
| 1 | Aastha | 7A | 2 | Mahira | 6A |
| 2 | Mahira | 6A | 2 | Mahira | 6A |
| 3 | Mohit | 7B | 2 | Mahira | 6A |
| 4 | Sanjay | 7A | 2 | Mahira | 6A |
| 1 | Aastha | 7A | 3 | Lavanya | 7A |
| 2 | Mahira | 6A | 3 | Lavanya | 7A |
| 3 | Mohit | 7B | 3 | Lavanya | 7A |
| 4 | Sanjay | 7A | 3 | Lavanya | 7A |
| 1 | Aastha | 7A | 4 | Sanjay | 7A |
| 2 | Mahira | 6A | 4 | Sanjay | 7A |
| 3 | Mohit | 7B | 4 | Sanjay | 7A |
| 4 | Sanjay | 7A | 4 | Sanjay | 7A |
| 1 | Aastha | 7A | 5 | Abhay | 8A |
| 2 | Mahira | 6A | 5 | Abhay | 8A |
| 3 | Mohit | 7B | 5 | Abhay | 8A |
| 4 | Sanjay | 7A | 5 | Abhay | 8A |
+------+--------+-------+------+---------+-------+

mysql> select now(); mysql> select dayname("2022-01-01")


+---------------------+ "2022 begins on";
| now() | +----------------+
+---------------------+ | 2022 begins on |
| 2021-12-30 13:15:03 | +----------------+
+---------------------+ | Saturday |
1 row in set (0.05 sec) +----------------+
1 row in set (0.02 sec)

76

You might also like