Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 34

This is the updated file which includes 18TH PROGRAM as per the syllabus released by CBSE this year

2022-23.

Dear Students,

Read ALL the instructions, before starting to write the record programs:

 Record Instructions:

A) Printout of index should be pasted (don’t write the index)

B) Each program should be written in a new page. (Don't write the programs continuously)

C) Right Side - Use only blue Gel/Ball pen (same pen) for writing all the exercises. W rite the Ex. No, page
number , TOPIC(which is given in index ) and Question, then leave one line space and write the program. Draw a line
at end of every program.
D) Left side (with pencil): Write the output in pencil.

E)Before submit the record , check whether the following are completed, 1. Eighteen python programs
and 4 sql programs with output. 2. Brown cover with school label 3. Index printout to be
pasted in the place provided. 4. Fill up the index with page number

SUBMIT THE RECORD ON REOPENING DAY - JUNE 1ST 2022

1
CHETTINAD VIDYASHRAM
STD XII – COMPUTER SCIENCE
RECORD PROGRAMS(2022-23)
1. Write a function for the following and get a choice and execute the same from main functions
1. To get a limit and print Fibonacci series in N terms
2. To get two limits and print all prime numbers between the limits
PROGRAM:
def FIBO(n):
if n <= 0:
print("Please enter a positive integer")
elif n == 1:
print("Fibonacci sequence upto",n,":")
print(0)
else:
print("Fibonacci sequence:")
a, b = 0, 1
for i in range(n):
print(a)
c=a+b
a=b
b=c
def PRIME(lower,upper):
if lower>upper:
lower,upper=upper,lower
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
while True:
print("\n1. Fibonacci series\n2. Prime numbers \n3. Exit\nEnter your Choice(1 to 3)...")
ch=int(input())
if ch==1:
n=int(input("How many terms?"))
FIBO(n)
elif ch==2:
lower=int(input("Enter two limits:"))
upper=int(input())
PRIME(lower,upper)
elif ch==3:
break
else:
print("Invalid choice")
2
OUTPUT:
1. Fibonacci series
2. Prime numbers
3. Exit
Enter your Choice(1 to 3)...
1
How many terms?5
Fibonacci sequence:
01123
1. Fibonacci series
2. Prime numbers
3. Exit
Enter your Choice(1 to 3)...
2
Enter two limits:1
10
Prime numbers between 1 and 10 are:
2357
1. Fibonacci series
2. Prime numbers
3. Exit
Enter your Choice(1 to 3)...
3

2. Write a function to find the sum of the following series using recursive function.

x+x2/2!+x3/3!+x4/4!......xn/n!

PROGRAM:
import math
def recur_fact(n):
if n == 1:
return n
else:
return n * recur_fact(n-1)

def sum(x,n):
s=0
for i in range(1,n+1):
s=s+pow(x,i)/recur_fact(i)
return s
x=int(input("Enter the X value"))
n=int(input("Enter the N value"))
print("Sum =",round(sum(x,n),2))
OUTPUT:

3
Enter the X value2
Enter the N value3
Sum = 5.33

3.Write a function that accept a multiword string as argument find and print the number of
occurrence and % of occurrence of alphabets, uppercase letters, lowercase letters, digits, spaces
and special characters along with main program.

PROGRAM:

def COUNT_PER(s):
al=uc=lc=di=sp=sc=c=0
for a in s:
if a.isalpha():
al+=1
if a.isupper():
uc+=1
else:
lc+=1
elif a.isdigit():
di+=1
elif a.isspace():
sp+=1
else:
sc+=1
l=len(s)
print("Number of alphabets:",al,"and its % of occurance:",round((al*100/l),2))
print("Number of uppercase letters:",uc,"and its % of occurance:",round((uc*100/l),2))
print("Number of lowercase letters:",lc,"and its % of occurance:",round((lc*100/l),2))
print("Number of digits:",di,"and its % of occurance:",round((di*100/l),2))
print("Number of spaces:",sp,"and its % of occurance:",round((sp*100/l),2))
print("Number of special characters:",sc,"and its % of occurance:",round((sc*100/l),2))

s=input("Enter a sentence:")
COUNT_PER(s)

OUTPUT:
Enter a sentence:I am studying CLASS 12 @ CV.
Number of alphabets: 18 and its % of occurance: 64.29
Number of uppercase letters: 8 and its % of occurance: 28.57
Number of lowercase letters: 10 and its % of occurance: 35.71
Number of digits: 2 and its % of occurance: 7.14
Number of spaces: 6 and its % of occurance: 21.43
Number of special characters: 2 and its % of occurance: 7.14

4. Write a function that accept N string values one by one, Count and print number of
palindrome strings, number of vowel strings( string starts with vowel character) and of
consonant strings( string starts with consonant character).

4
PROGRAM:
def PALIND(s):
if s==s[::-1]:
return 1
else:
return 0
def CHECK(s):
vow="aeiouAEIOU"
if s.isalpha():
if s[0] in vow:
return 'v'
else:
return 'c'

n=int(input("How many strings?"))


p=v=c=0
print("Enter ", n, " Strings:")
for i in range(n):
a=input()
if PALIND(a)==1:
p+=1
res=CHECK(a)
if res=='v':
v+=1
elif res=='c':
c+=1
print("\n Number of palindrome strings:",p)
print("\n Number of vowel strings:",v)
print("\n Number of consonant strings:",c)

OUTPUT:

How many strings?7


Enter 7 Strings:
JASMINE
ROSE
ALOEVERA
ORCHID
LIRIL
TULIP
IRISES

Number of palindrome strings: 1


Number of vowel strings: 3
Number of consonant strings: 4

5.Write a function that accepts an integer list as argument find and print the second maximum and
second minimum number in the given list.

PROGRAM:

5
def SECOND_MAX_MIN(lis,n):
lis.sort(reverse=True)
for i in range(len(lis)-1):
if lis[i]>lis[i+1]:
print("Second max=",lis[i+1])
break
else:
print("There is no second max as All are equal")

lis.sort()
for i in range(len(lis)-1):
if lis[i]<lis[i+1]:
print("Second min=",lis[i+1])
break
else:
print("There is no second min as All are equal")

a=[]
n=int(input("How many values:"))
print("Enter ",n," values:")
for i in range(n):
a.append(int(input()))
SECOND_MAX_MIN(a,n)

OUTPUT 1:
How many values:5
Enter 5 values:
3
3
3
3
3
There is no second max as All are equal
There is no second min as All are equal

OUTPUT 2:
How many values:6
Enter 6 values:
4
60
50
3
-4
10
Second max= 50
Second min= 3

6. Write a function that accepts an integer list as argument and shift all odd numbers to the left

6
and even numbers to the right of the list without changing the order.

eg. List before shifting: [12,15,10,5,8,9]


List after shifting : [15, 5, 9, 12, 10, 8] )

PROGRAM:
def SHIFT(a,n):
c=0
for i in range(n):
if a[i]%2!=0:
x=a.pop(i)
a.insert(c,x)
c+=1

a=[]
n=int(input("How many values:"))
print("Enter ",n," values:")
for i in range(n):
a.append(int(input()))
print("List values before shifting:",a )
SHIFT(a,n)
print("List values after shifting:",a )

OUTPUT:
How many values:6
Enter 6 values:
12
15
10
5
8
9
List values before shifting: [12, 15, 10, 5, 8, 9]
List values after shifting: [15, 5, 9, 12, 10, 8]

7. Write a function that accept N strings in a tuple as argument, Find and print the longest and
shortest string of N strings (Lengthwise). Also find and print the greatest and smallest string
of N strings (Alphabetical order) along with main program.

PROGRAM:

7
def FIND_LONG_SHORT(s,n):
long=short=s[0]
for a in s:
if len(a)>len(long):
long=a
elif len(a)<len(short):
short=a
print("Longest string is:",long) ;
print("Shortest string is:",short)

def FIND_GREAT_SMALL(s,n):
great=small=s[0]
for a in s:
if a>great:
great=a
elif a<small:
small=a
print("Greatest string is:",great)
print("Smallest string is:",small)

t=()
n=int(input("How many strings:"))
print("Enter ", n ," Strings:")
for i in range(n):
t+=(input(),)
FIND_LONG_SHORT(t,n)
FIND_GREAT_SMALL(t,n)

OUTPUT:
How many strings:5
Enter 5 Strings:
CHENNAI
THIRUVANANATHAPURAM
GOA
PUNE
VIJAYAWADA
Longest string is: THIRUVANANATHAPURAM
Shortest string is: GOA
Greatest string is: VIJAYAWADA
Smallest string is: CHENNAI

8. Write a program to create a dictionary with salesman code as key and a tuple with elements
like name, product type, sale amount and commission for N salesmen. Also write a
function to display the result as given format. Commission calculation:

Product Type % of commission on Sale

8
Amount Medicine 20%
Food 25 %
Garments 18%
other products 15%

Result should be printed as follows

S. No Code Name Prod. Type Sale Amount Commission


1
2
3
.
.

PROGRAM:

def ACCEPT(d,n):
for i in range(n):
t=()
code=int(input("Enter salesman code:"))
t+=(input("Enter name:"),)
t+=(input("Enter Product Type:"),)
t+=(float(input("Enter Purchase Amount:")),)
if t[1].upper()=="MEDICINE":
comm=t[2]*.2
elif t[1].upper()=="FOOD":
comm=t[2]*.25
elif t[1].upper()=="GARMENT":
comm=t[2]*.18
else:
comm=t[2]*.15
t+=(comm,)
d[code]=t

def PRINT(d,n):
c=1
print('-'*70)
print("S.No\tCode\tName\tProd Type\tPur. Amt.\tCommission")
print('-'*70)
for i,j in d.items():
print(c,"\t",i,"\t",j[0],"\t",j[1],"\t \t",j[2],"\t\t",j[3])
c+=1

d={}
n=int(input("How many salesmen?"))
ACCEPT(d,n)
PRINT(d,n)

OUTPUT:

9
How many salesmen?4
Enter salesman code:101
Enter name:CROCIN
Enter Product Type:MEDICINE
Enter Purchase Amount:300
Enter salesman code:102
Enter name:SUGAR
Enter ProductType:FOOD
Enter Purchase Amount:650
Enter salesman code:103
Enter name:T-SHIRT
Enter Product
Type:GARMENT
Enter Purchase Amount:2250
Enter salesman code:104
Enter name:PONDS
Enter Product Type:COSMETIC
Enter Purchase Amount:525
----------------------------------------------------------------------------------------------
S.No Code Name Prod Type Pur. Amt. Commission
----------------------------------------------------------------------------------------------
1 101 CROCIN MEDICINE 300.0 60.0
2 102 SUGAR FOOD 650.0 162.5
3 103 T-SHIRT GARMENT 2250.0 405.0
4 104 PONDS COSMETIC 525.0 78.75

9. Write a program to create a dictionary with game as key and list with elements like player
name, country name and points for N players. Write a function to arrange the players in
alphabetical order of game and display the details in the sorted order of game.

PROGRAM:

def INPUT(d,n):
for i in range(n):
game=input("Enter the game:")
p=list()
p.append(input("Enter player name:"))
p.append(input("Enter Country name:"))
p.append(int(input("Enter the points:")))
d[game]=p
print('-'*100)

def SHOW(d,n):
print("\nRecords in Ascending order of Game:")
for k in sorted(d,reverse= False):
print(k,d[k])
print('-'*100)

d={}

10
n=int(input("How many Games:"))
INPUT(d,n)
print("Records in DICTIONARY")
print(d)
print('-'*100)
SHOW(d,n)

OUTPUT:
How many Games:3
Enter the game:FOOTBALL
Enter player name:MESSI
Enter Country name:ARGENTINE
Enter the points:689
Enter the game:HOCKEY
Enter player name:SREEJESH PR
Enter Country name:INDIA
Enter the points:756
Enter the game:CRICKET
Enter player name:DHONI
Enter Country name:INDIA
Enter the points:789
----------------------------------------------------------------------------------------------------------------
Records in DICTIONARY
{'FOOTBALL': ['MESSI', 'ARGENTINE', 689], 'HOCKEY': ['SREEJESH PR', 'INDIA', 756],
'CRICKET': ['DHONI', 'INDIA', 789]}
-----------------------------------------------------------------------------------------------------------------
Records in Ascending order of Game:
CRICKET ['DHONI', 'INDIA', 789]
FOOTBALL ['MESSI', 'ARGENTINE', 689]
HOCKEY ['SREEJESH PR', 'INDIA', 756]
--------------------------------------------------------------------------------------------------------------------

10. Write a program to create a dictionary with game as key and list with elements like player
name, country name and points for N players. Write a function to search for the given country
name and print the details of players. Also the function should accept the name of game and
update the points by 15% of existing points and display the updated records.
PROGRAM:
def INPUT(d,n):
for i in range(n):
game=input("Enter the game:")
p=list()
p.append(input("Enter player name:"))
p.append(input("Enter Country name:"))
p.append(int(input("Enter the points:")))
d[game]=p
print('-'*100)
print("\nRecords in Dictionary")
print(d)
print('-'*100)

11
def SEARCH(d,n,coun):
flag=0
for key in d.keys():
if d[key]
[1]==coun:
print(key,d[key])
flag+=1
if flag==0:
print("Searching country not found")
print('-'*100)

def MODIFY(d,n,game):
flag=0
for key in d.keys():
if key==game:
d[key][2]+=d[key][2]*.15
flag+=1
if flag==0:
print("Searching country not found")
else:
print(flag, "Records updated")
print('-'*100)

d={}
n=int(input("How many Games:"))
INPUT(d,n)
coun=input("Enter country name to be searched:")
SEARCH(d,n,coun);
game=input("Enter game name to increase the points:")
MODIFY(d,n,game)
print("Records after updation:")
print(d)
print('-'*100)

OUTPUT:

How many Games:3


Enter the game:FOOTBALL
Enter player name:MESSI
Enter Country name:ARGENTINE
Enter the points:3453
Enter the game:HOCKEY
Enter player name:SREEJESH
Enter Country name:INDIA
Enter the points:675
Enter the game:CRICKET
Enter player name:DHONI

12
Enter Country name:INDIA
Enter the points:789
--------------------------------------------------------------------------------------------------------------
Records in Dictionary
{'FOOTBALL': ['MESSI', 'ARGENTINE', 3453], 'HOCKEY': ['SREEJESH', 'INDIA', 675],
'CRICKET': ['DHONI', 'INDIA', 789]}
--------------------------------------------------------------------------------------------------------------
Enter country name to be searched:INDIA
HOCKEY ['SREEJESH', 'INDIA', 675]
CRICKET ['DHONI', 'INDIA', 789]
--------------------------------------------------------------------------------------------------------------
Enter game name to increase the points:HOCKEY
1 Records updated
---------------------------------------------------------------------------------------------------------------
Records after updation:
{'FOOTBALL': ['MESSI', 'ARGENTINE', 3453], 'HOCKEY': ['SREEJESH', 'INDIA', 776.25],
'CRICKET': ['DHONI', 'INDIA', 789]}

11. Write a program with functions to create a text file called school.txt, store information and
print the same. Also write another function to copy all the lines to the new file called
myschool.txt which are do not have word ‘It’ anywhere in the line and display the new file.
PROGRAM:

def CREATE():
f=open("school.txt","w")
print("Enter information about school and 'exit' to stop")
while True:
s=input()
if s.upper()=='EXIT':
break
f.write(s)
f.write('\n')
f.close()

def PRINT(a):
f=open(a,"r")
s=" "
while s:
s=f.readline()
print(s,end="")
f.close()

13
def COPY():
f1=open("school.txt","r")
f2=open("myschool.txt","w")
s=" "
while s:
s=f1.readline()
if 'It'.upper() in s.upper():
pass
else:
f2.write(s)
f1.close()
f2.close()

CREATE()
print("CONTENT OF SCHOOL.TXT FILE:")
PRINT("school.txt")
COPY()
print("CONTENT OF MYSCHOOL.TXT FILE:")
PRINT("myschool.txt")

OUTPUT:

Enter information about school and 'exit' to stop CV IS BEST.


IT IS IN CHENNAI. CV IS BIG.
EXIT
CONTENT OF SCHOOL.TXT FILE:
CV IS BEST.
IT IS IN CHENNAI. CV IS BIG.
CONTENT OF MYSCHOOL.TXT FILE:
CV IS BEST. CV IS BIG.

12. Write functions to create a text file called marina.txt to store information about marina beach,
read the data, find and print the occurrence of most 5 common words present in the file.

PROGRAM:

def CREATE():
f=open("marina.txt","w")
print("Enter information about marina beach and 'exit' to stop:")
while True:
s=input()
if s.upper()=='EXIT':
break
f.write(s)
f.write('\n')
f.close()

14
def PRINT():
f=open("marina.txt","r")
s=" "
print("FILE CONTENT:")
while s:
s=f.readline()
print(s,end="")
f.close()

def Find_Common():
f=open("marina.txt","r")
s=" "
d=dict()
while s:
s=f.readline()
s=s.rstrip("\n")
a=s.split()
for i in a:
if i in d.keys():
d[i]+=1
else:
d[i]=1 # first occurance
c=0
print("\nCommon Frequency of 5 words:")
for k in sorted(d,key=d.get,reverse=True):
print(k,"\t:",d[k]) #
c+=1
if c==5:
break
f.close()

CREATE()
PRINT()
Find_Common()

OUTPUT:
Enter information about marina beach and 'exit' to stop:
MARINA BEACH IS A NATURAL URBAN BEACH IN
CHENNAI. MARINA BEACH IS SECOND LONGEST BEACH
IN THE WORLD. EXIT
FILE CONTENT:
MARINA BEACH IS A NATURAL URBAN BEACH IN
CHENNAI. MARINA BEACH IS SECOND LONGEST BEACH
IN THE WORLD.

Common Frequency of 5 words:


BEACH 4
MARINA 2
IS 2
IN 2
A 1

15
13. A binary file “emp.dat” has structure [empno, empname,salary]. Write a user defined function
CreateEmp() to input data for a record and add to emp.dat and display the details using
DISPLAY() function. Write Search() function that would read contents of the file emp.dat and
display the details of those employees whose salary is greater than 10000.

PROGRAM:
import pickle
def validate_empno():
with open("emp.dat",'rb') as f:
en=int(input("Enter emp no."))
try:
while True:
a = pickle.load(f)
if en == a[0]:
print("\nEmp no. is already exists!!!")
return -1
except EOFError:
return en

def CreateEmp():
with open("emp.dat",'wb') as f:
n=int(input("Enter how many employees"))
for i in range(n):
lis=[]
eno=validate_empno()
if eno==-1:
break
ename=input("Enter employee name")
salary=int(input("Enter basic salary"))
lis=[eno,ename,salary]
pickle.dump(lis,f)
f.flush()
f.close()

def DISPLAY():
with open("emp.dat",'rb') as f: print("\
nContents of the file") print("\nEMPNO\
tEMPNAME\tSALARY") try:
while True:
a = pickle.load(f)
print(a[0],a[1],a[2],sep='\t')
except EOFError:
return

def Search():

16
with open("emp.dat",'rb') as f:
print("\nSalary more than 10000")
print("\nEMPNO\tEMPNAME\tSALARY")
try:
while True:
a = pickle.load(f)
if a[2]>10000:
print(a[0],a[1],a[2],sep='\t')
except EOFError:
return
CreateEmp()
DISPLAY()
Search()

OUTPUT:

Enter how many employees3


Enter emp no.10
Enter employee namearun
Enter basic salary12000
Enter emp no.20
Enter employee namekumar
Enter basic salary9000
Enter emp no.30
Enter employee nameshyam
Enter basic salary13000

Contents of the file

EMPNO EMPNAME SALARY


10 arun 12000
20 kumar 9000
30 shyam 13000

Salary more than 10000

EMPNO EMPNAME SALARY


10 arun 12000
30 shyam 13000

14. A binary file “emp.dat” has structure [empno, empname,salary]. Write a user defined function
CreateEmp() to input data for a record and add to emp.dat . Also write a function DELETE() to
accept an employee number and delete the details. Function should display the file contents
before and after deletion of employee record using DISPLAY() function.

17
PROGRAM:
import pickle
def validate_empno():
with open("emp.dat",'rb') as f:
en=int(input("Enter emp no."))
try:
while True:
a = pickle.load(f)
if en == a[0]:
print("\nEmp no. is already exists!!!")
return -1
except EOFError:
return en
def CreateEmp():
f=open("emp.dat",'wb')
n=int(input("Enter how many employees"))
for i in range(n):
lis=[]
eno=validate_empno()
if eno==-1:
break
ename=input("Enter employee name")
salary=int(input("Enter basic salary"))
lis=[eno,ename,salary]
pickle.dump(lis,f)
f.flush()
f.close()

def DISPLAY():
with open("emp.dat",'rb') as f: print("\
nContents of the file") print("\nEMPNO\
tEMPNAME\tSALARY") try:
while True:
a = pickle.load(f)
print(a[0],a[1],a[2],sep='\t')
except EOFError:
return

def DELETE():

18
import os
flag=0
en=int(input("Enter the emp no. to delete"))
with open("emp.dat",'rb') as f, open("tem.dat",'wb') as f2:
try:
while True:
a = pickle.load(f)
if en != a[0]:
pickle.dump(a,f2)
f2.flush()
else:
flag=1
except EOFError:
pass
if flag==0:
print("\nEmp no. is not found!")
return
else:
print("\nRecord is deleted!")
os.remove('emp.dat')
os.rename('tem.dat','emp.dat')

CreateEmp()
DISPLAY()
DELETE()
print("\nAfter Delete")
DISPLAY()

OUTPUT:
Enter how many employees3
Enter emp no.10
Enter employee namearun
Enter basic salary12000
Enter emp no.20
Enter employee namekumar
Enter basic salary8000
Enter emp no.30
Enter employee nameshyam
Enter basic salary14000

Contents of the file

EMPNO EMPNAME SALARY

19
10 arun 12000
20 kumar 8000
30 shyam 14000
Enter the emp no. to delete20

Record is deleted!
After Delete
Contents of the file

EMPNO EMPNAME SALARY


10 arun 12000
30 shyam 14000

15. Write a function create() to create CSV file student.csv which accepts rollno,name,sec and average
marks for N students. Write 2 more functions show() and show2() to display all the details and to display
the students those who have got the average marks >=80, respectively.
PROGRAM:
import csv
def create():
f=open("student.csv",'w',newline="")
writer=csv.writer(f)
writer.writerow(["\nrollno",'name','section','Avg_marks\n'])
while True:
r=int(input("Enter the rollno:"))
n=input("Enter the name:")
g=input("Enter the section:")
m=int(input("Enter the Avg marks:"))
data=[r,n,g,m]
writer.writerow(data)
ch=input("press any key to continue?N to exit\n")
if ch in 'nN':
break
f.close()

def show():
f=open("student.csv",'r')
reader=csv.reader(f)
for a in reader:
print(a[0],a[1],a[2],a[3],sep='\t')
f.close()

def show2():

20
f=open("student.csv",'r')
reader=csv.reader(f)
header=next(reader) # to skip headings, next() returns first row to header

for a in reader: # iterate from second row


if int(a[3]) >=80: # int() fn is given as the data stored as string in csv
print(a[0],a[1],a[2],a[3],sep='\t')
f.close()

create()
print("All the students details")
show()
print("\nStudents who have got average >=80\n")
show2()

OUTPUT:
Enter the rollno:1
Enter the name:PAVI
Enter the section:D
Enter the Avg marks:79
press any key to continue?N to exit
C
Enter the rollno:2
Enter the name:KAVI
Enter the section:A
Enter the Avg marks:85
press any key to continue?N to exit
F
Enter the rollno:3
Enter the name:CIBI
Enter the section:F
Enter the Avg marks:90
press any key to continue?N to exit
N
All the students details

rollno name section Avg_marks

1 PAVI D 79
2 KAVI A 85
3 CIBI F 90

Students who have got average >=80

2 KAVI A 85
3 CIBI F 90

16.Write a function create() to create password.csv which accepts user id and password.

21
Write function show() to display all the details, show2() to accept the user id and print the
password if the user id is present otherwise print the error message 'user id is not present”

import csv
def create():
f=open("password.csv",'w',newline="")
writer=csv.writer(f)
writer.writerow(["User Name",'Password'])
while True:
r=input("Enter the User id:")
n=input("Password:")
data=[r,n]
writer.writerow(data)
ch=input("press any key to continue?N to exit\n")
if ch in 'nN':
break
f.close()

def show():
f=open("password.csv",'r')
reader=csv.reader(f)
for a in reader:
print(a[0],'\t',a[1])

f.close()

def show2():
f=open("password.csv",'r')
id=(input("Enter the User id to search password:"))
reader=csv.reader(f)
header=next(reader) # to skip headings, next() returns first row to header

for a in reader: # iterate from second row


if a[0]==id:
print("Password :",a[1])
break
else:
print("User id is not present")
f.close()

create()
show()
show2()

OUTPUT

22
Enter the User id:covid2019
Password:corona
press any key to continue?N to exit
y
Enter the User id:italy 2017
Password:venice
press any key to continue?N to exit
n
User Name Password
covid2019 corona
italy 2017 venice
Enter the User id to search password:italy 2017
Password : venice

17. Write a menu driven programs with functions for a list of integer values using STACK techniques
1. INSERT
2. DELETE
3. DISPLAY
4. EXIT

PROGRAM:
a=[]

def Push(val):
a.append(val)
print("Value ",val," is inserted")

def Pop():
if a==[]:
print("Stack is empty")
else:
print("Deleted value is:",a.pop())

def Display():
if a==[]:
print("Stack is empty")
else:
print("Stack values:")
for i in range(len(a)-1,-1,-1):
print(a[i],end=" ")
while True:
print("\n1. Insert\n2. Delete\n3. Display\n4. Exit")
ch=int(input("Enter Your choice:"))

if ch==1:

23
val=int(input("Enter any value:"))
Push(val)
elif ch==2:
Pop()
elif ch==3:
Display()
elif ch==4:
break
else:
print("Invalid choice")

OUTPUT:

1. Insert
2. Delete
3. Display
4. Exit
Enter Your choice:1
Enter any value:10
Value 10 is inserted

1. Insert
2. Delete
3. Display
4. Exit
Enter Your choice:1
Enter any value:20
Value 20 is inserted

1. Insert
2. Delete
3. Display
4. Exit
Enter Your choice:1
Enter any value:30
Value 30 is inserted

1. Insert
2. Delete
3. Display
4. Exit
Enter Your choice:3
Stack values:
30 20 10
1. Insert
2. Delete
3. Display
4. Exit
Enter Your choice:2

24
Deleted value is: 30

1. Insert
2. Delete
3. Display
4. Exit
Enter Your choice:3
Stack values:
20 10
1. Insert
2. Delete
3. Display
4. Exit
Enter Your choice:4

25
Note: Queue program is given below as 18th prg which is updated in this file. Those
who have already written all the 17 programs and 4 sql programs, can write the 18th
program as a last program after sql.

18. Write a menu driven programs with functions for a list of integer values using QUEUE techniques
1. INSERT
2. DELETE
3. DISPLAY
4. EXIT
PROGRAM:
a=[]
def Enqueue(val):
a.append(val)
print("Value ",val," is inserted")

def Dequeue():
if a==[]:
print("Queue is empty")
else:
print("Deleted value is:",a.pop(0))

def Display():
if a==[]:
print("Queue is empty")
else:
print("Queue values:")
for i in range(len(a)):
print(a[i],end=" ")
while True:
print("\n1. Insert\n2. Delete\n3. Display\n4. Exit")
ch=int(input("Enter Your choice:"))
if ch==1:
val=int(input("Enter any value:"))
Enqueue(val)
elif ch==2:
Dequeue()
elif ch==3:
Display()
elif ch==4:
break
else:
print("Invalid choice")

OUTPUT:

26
1. Insert
2. Delete
3. Display
4. Exit
Enter Your choice:1
Enter any value:10
Value 10 is inserted

1. Insert
2. Delete
3. Display
4. Exit
Enter Your choice:1
Enter any value:20
Value 20 is inserted

1. Insert
2. Delete
3. Display
4. Exit
Enter Your choice:1
Enter any value:30
Value 30 is inserted

1. Insert
2. Delete
3. Display
4. Exit
Enter Your choice:3
Queue values:
10 20 30
1. Insert
2. Delete
3. Display
4. Exit
Enter Your choice:2
Deleted value is: 10

1. Insert
2. Delete
3. Display
4. Exit
Enter Your choice:3
Queue values:
20 30
1. Insert
2. Delete
3. Display
4. Exit
Enter Your choice:4
SQL
27
1. Write a program to connect Python with MYSQL using database connectivity for the table STUDENT
given below and perform the following.
----------------------------------------------------------------------------------------------------------------------
Roll Name Stipend Stream Avgmark Grade Class
----------------------------------------------------------------------------------------------------------------------
101 Karan 400 Medical 78.5 B 12
102 Divakar 450 Commerce 89.2 A 11
103 Divya 300 Commerce 68.6 C 12
104 Arun 350 Medical 85.5 D 12
105 Sophy 600 Biology 90.3 A 11
----------------------------------------------------------------------------------------------------------------

1. Select all the medical stream student from the student table.
2. To display stream and number of students in each stream of the given table student.
3. List the name and grade whose avgmark is above 85.
4. Display the total of stipend whose grade is A.
5. To increase the stipend by 200 whose grade is A.
PROGRAM:

import mysql.connector
con=mysql.connector.connect(host='localhost',user='root',password='root',charset='utf8')
cur=con.cursor()

cur.execute("create database if not exists practical")


cur.execute("use practical")

cur.execute("create table if not exists student (roll int primary key, name char(20),stipend int, stream
char(10), avgmark int, grade char, class int)")
print("Table created")

cur.execute("insert ignore into student values(101,'Karan',400,'Medical', 78.5,'B',12)")


cur.execute("insert ignore into student values(102,'Divakar',450,'Commerce', 89.5,'A',11)")
cur.execute("insert ignore into student values(103,'Divya',300,'Commerce', 68.6,'C',12)")
cur.execute("insert ignore into student values(104,'Arun',350,'Medical', 85.5,'D',12)")
cur.execute("insert ignore into student values(105,'Sophy',600,'Biology', 90.3,'A',11)")

con.commit()
print("Records inserted")

print("1.")
cur.execute("select * from STUDENT where STREAM='Medical' ")
data=cur.fetchall()
for x in data:
print(x)

print("2.")
cur.execute("select STREAM, count(*) from STUDENT group by STREAM")
for x in cur:
print(x)

28
print("3.")
cur.execute("select NAME, GRADE from STUDENT where AVGMARK>85")
for x in cur:
print(x)

print("4.")
cur.execute("select sum(stipend) from STUDENT where grade = 'A' ")
for x in cur:
print(x[0])

print("5.")
cur.execute("update student set stipend=stipend+200 where grade='A' ")
print("Record updated")

con.commit()
cur.close()
con.close()

OUTPUT:

Table created
Records inserted

1.
(101, 'Karan', 400, 'Medical', 79, 'B', 12)
(104, 'Arun', 350, 'Medical', 86, 'D', 12)
2.
('Biology', 1)
('Commerce', 2)
('Medical', 2)
3.
('Divakar', 'A')
('Arun', 'D')
('Sophy', 'A')
4.
1050
5.
Record updated

2. Write a program to connect Python with MYSQL using database connectivity for the table SALES given
below and perform the following.
----------------------------------------------------------------------------------------------------------------
NAME PRODUCT QTY_TAR PRICE COMMISSION
----------------------------------------------------------------------------------------------------------------
Santhosh Lux 50 15.35 120
Praveen Harpic 25 40.25 150
Kumar Britannia 20 11.25 100
Arjun Glaxo 30 67.85 150
Jacob Hamam 40 11.50 200

1. Display all the records of those QTY_TAR is more than 35 and arranged by ascending order of product.

29
2. Select the name and product where the product as Britannia and the commission>=100
3. To display the number of tuples available in the table.
4. Select and display the maximum price and minimum price of the table sales.
5. Delete the record whose commission is 150.
PROGRAM :
import mysql.connector
con=mysql.connector.connect(host='localhost',user='root',password='root',charset='utf8')
cur=con.cursor()

cur.execute("create database if not exists practical")


cur.execute("use practical")
cur.execute("create table if not exists sales(Name char(20) not null, product char(10), Qty_tar int, price
double, commission int)")
print("Table created")

cur.execute("insert ignore into sales values('Santhosh','Lux',50,15.35,120)")


cur.execute("insert ignore into sales values('Praveen','Harpic',25,40.25,150)")
cur.execute("insert ignore into sales values('Kumar','Britannia',20,11.25,100)")
cur.execute("insert ignore into sales values('Arjun','Glaxo',30,67.85,150)")
cur.execute("insert ignore into sales values('Jacob','Hamam',40,11.50,200)")

con.commit()
print("Records inserted")

print("1.")
cur.execute("select * from SALES where QTY_TAR>35 order by PRODUCT ")
for x in cur:
print(x)
print("2.")
cur.execute(" select NAME, PRODUCT from SALES where PRODUCT ='Britannia' and
COMMISSION>=100")
for x in cur:
print(x)
print("3.")
cur.execute("select count(*) from SALES ")
for x in cur:
print(x)
print("4.")
cur.execute("select max(price), min(price) from SALES")
for x in cur:
print(x)
print("5.")
cur.execute("delete from sales where commission=150")
print("Record Deleted")

con.commit()
cur.close()
con.close()

OUTPUT:

30
Table created
Records inserted
1.
('Jacob', 'Hamam', 40, 11.5, 200)
('Santhosh', 'Lux', 50, 15.35, 120)
2.
('Kumar', 'Britannia')
3.
(5,)
4.
(67.85, 11.25)
5.
Record Deleted

3. Write a program to connect Python with MYSQL using database connectivity for the table MOVIE given
below and perform the following.
----------------------------------------------------------------------------------------------------------------
TITLE TYPE RATING STARS QTY PRICE
----------------------------------------------------------------------------------------------------------------
Liar Liar Comedy PG13 Jim Carre 5 25.35
Lost World Horror PG Melgibson 4 35.45
The specialist Action G Stallon 3 40.23
Down Periscope Comedy PG13 Stone 6 43.25
Conair Action G Nicholas 3 55.25
----------------------------------------------------------------------------------------------------------------
1. Display the maximum price from movie table.
2. List all the stars name starts with ‘S’.
3. Display all the details arranged by ascending order of title.
4. Display the title where price is more than 20.
5. To change the value of quantity as 10 those movie type is comedy.
PROGRAM:
import mysql.connector
con=mysql.connector.connect(host='localhost',user='root',password='root',charset='utf8')
cur=con.cursor()

cur.execute("create database if not exists practical")


cur.execute("use practical")

cur.execute("create table if not exists movie (title char(20) primary key, type char(10), rating char(15), stars
char(10), qty int, price float)")
print("Table created")

cur.execute("insert ignore into movie values('Liar Liar','Comedy','PG13','JimCarre',5,25.35)")


cur.execute("insert ignore into movie values('Lost World','Horror','PG','Melgibson',4,35.45)")
cur.execute("insert ignore into movie values('The specialist','Action','G','Stallon',3,40.23)")
cur.execute("insert ignore into movie values('Down Periscope','Comedy','PG13','Stone',6,43.25)")
cur.execute("insert ignore into movie values('Conair','Action','G','Nicholas',3,55.25)")
con.commit()
print("Records inserted")

31
print("1.")
cur.execute("select max(price) from movie")
for x in cur:
print(x)

print("2.")
cur.execute("select stars from MOVIE where STARS like 'S%'")
for x in cur:
print(x)

print("3.")
cur.execute("select * from MOVIE order by TITLE ")
for x in cur:
print(x)

print("4.")
cur.execute("select TITLE from MOVIE where PRICE>20")
for x in cur:
print(x)

print("5.")
cur.execute("update movie set qty=10 where type='comedy' ")
print("Record updated")
con.commit()
cur.close()
con.close()

OUTPUT:

Table created
Records inserted
1.
(55.25,)
2.
('Stone',)
('Stallon',)
3.
('Conair', 'Action', 'G', 'Nicholas', 3, 55.25)
('Down Periscope', 'Comedy', 'PG13', 'Stone', 10, 43.25)
('Liar Liar', 'Comedy', 'PG13', 'Jim Carre', 10, 25.35)
('Lost World', 'Horror', 'PG', 'Melgibson', 4, 35.45)
('The specialist', 'Action', 'G', 'Stallon', 3, 40.23)
4.
('Conair',)
('Down Periscope',)
('Liar Liar',)
('Lost World',)
('The specialist',)
5.
Record updated

32
4. Write a program to connect Python with MYSQL using database connectivity for the table LIBRARY
given below and perform the following.
----------------------------------------------------------------------------------------------------------------
BID TITLE AUTHOR TYPE PUB QTY PRICE
----------------------------------------------------------------------------------------------------------------
101 Data structure Lipchutz DS McGraw 4 217
102 Advanced Pascal Schildt PROG BPB 5 350
103 Mastering C++ Gurewich PROG PHI 3 130
104 Mastering Window Cowart OS BPB 6 40
105 Network Guide Freed NET Zpress 5 200
----------------------------------------------------------------------------------------------------------------

1. Display all the details of those type is PROG and publisher is BPB.
2. Display all the details with price more than 130 and arranged by ascending order of qty.
3. Display the number of books published by BPB.
4. Display the title and qty for those qty between 3 and 5.
5. Delete the record whose type is PROG.
PROGRAM:
import mysql.connector
con=mysql.connector.connect(host='localhost',user='root',password='root',charset='utf8')
cur=con.cursor()
cur.execute("create database if not exists practical")
cur.execute("use practical")
cur.execute("create table if not exists library (bid int primary key, title char(20) not null ,author char(10),
type char(10), pub char(10), qty int, price int)")
print("Table created")

cur.execute("insert ignore into library values(101,'Data structure','Lipchutz','DS','McGraw',4,217)")


cur.execute("insert ignore into library values(102,'AdvancedPascal','Schildt','PROG','BPB',5,350)")
cur.execute("insert ignore into library values(103,'Mastering C++','Gurewich','PROG','PHI',3,130)")
cur.execute("insert ignore into library values(104,'Mastering Window','Cowart','OS','BPB',6,40)")
cur.execute("insert ignore into library values(105,'Network Guide','Freed','NET','Zpress',5,200)")

con.commit()
print("Records inserted")

print("1.")
cur.execute("select * from library where TYPE='PROG' and PUB ='BPB' ")
for x in cur:
print(x)

print("2.")
cur.execute("select * from library where PRICE>130 order by QTY ")
for x in cur:
print(x)

print("3.")
cur.execute("select count(*) from library where PUB='BPB' ")
for x in cur:
print(x)

33
print("4.")
cur.execute("select title,qty from library where qty between 3 and 5")
for x in cur:
print(x)

print("5.")
cur.execute("delete from library where type='PROG' ")
print("Record deleted")
con.commit()
cur.close()
con.close()

OUTPUT:

Table created
Records inserted
1.
(102, 'Advanced Pascal', 'Schildt', 'PROG', 'BPB', 5, 350)
2.
(101, 'Data structure', 'Lipchutz', 'DS', 'McGraw', 4, 217)
(102, 'Advanced Pascal', 'Schildt', 'PROG', 'BPB', 5, 350)
(105, 'Network Guide', 'Freed', 'NET', 'Zpress', 5, 200)
3.
(2,)
4.
('Data structure', 4)
('Advanced Pascal', 5)
('Mastering C++', 3)
('Network Guide', 5)
5.
Record deleted

*****

34

You might also like