0% found this document useful (0 votes)
29 views

Class 12 CS Practical file

Study material for class 12 ncert cbse

Uploaded by

infantisrel290
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)
29 views

Class 12 CS Practical file

Study material for class 12 ncert cbse

Uploaded by

infantisrel290
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/ 33

Dear Students,

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

Record Instructions:

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

B) Right Side - Use only blue Gel/Ball pen (same pen) for writing all the exercises. .
C) Left side (with pencil): Write the output in pencil.

D) Before submit the record , check whether the following are completed,

E) Sample aim and result is specified for the first 2 programs, similar aim and result should be made for the rest of the
programs.

1. Seventeen python programs with output and 4 sql programs with output.
2. Brown cover

SUBMIT THE RECORD ON REOPENING DAY - OCTOBER 18 TH 2024

1
PM SHRI KV MANDAPAM
STD XII – COMPUTER
SCIENCE

RECORD PROGRAMS(2024-25)

1.
AIM:
To Write a Python program with 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):
f1,f2=-1,1
for i in range(n):
f3=f1+f2
print(f3)
f1,f2=f2,f3

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")

OUTPUT:
1. Fibonacci series
2. Prime numbers
2
3. Exit
Enter your Choice(1 to 3)...

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
RESULT:
Thus a Python program with functions for finding prime numbers within a limit and printing Fibonacci
series are created and the output is verified with sample input.
2.
AIM:
To write a function in Python that accept a multiword string as argument find and print the
number of occurrence and % of occurrence of alphabets, uppercase letters, lowercase letters,
digits, spacesand 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)

4
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))

5
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
RESULT:
Thus a Python program with functions for performing string based operations is created and the output is
verified with sample input.

3.
AIM:
To write a function in Python that accept N string values one by one, Count and print number of
palindromestrings, number of vowel strings( string starts with vowel character) and of consonant
strings( string starts with consonant character).
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
6
print("\n Number of palindrome strings:",p)
print("\n Number of vowel strings:",v)
print("\n Number of consonant strings:",c)

7
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

4. 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:

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

8
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

5. Write a function that accepts an integer list as argument and shift all odd numbers to the left
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]

9
6. 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:

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

10
7. 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
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)

11
OUTPUT:
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

8. 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:").title()
p=list()
p.append(input("Enter player name:").title())
p.append(input("Enter Country name:").title())
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)

12
d={}
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]

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

13
print('-'*100)
print("\nRecords in Dictionary")
print(d)
print('-'*100)

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

14
Enter the game:CRICKET
Enter player name:DHONI
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]}

10. 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’ any where 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+'\n')
f.close()

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

def COPY():
f1=open("school.txt","r")
f2=open("myschool.txt","w")
for s in f1:
if 'IT' not in s.upper():
f2.write(s)

15
f1.close()
f2.close()

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.

11. 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+'\n')
f.close()

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

def Find_Common():
f=open("marina.txt","r")
d=dict()
for s in f:
for i in s.split():
if i in d.keys():
d[i]+=1
else:
d[i]=1

16
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

12. 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():
f=open("emp.dat",'rb'):
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:
f.close()
return en

17
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.close()

def DISPLAY():
f=open("emp.dat",'rb')
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:
f.close()
return

def Search():
f=open("emp.dat",'rb')
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:
f.close()
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

18
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

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 . 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.
PROGRAM:

import pickle
import os
def validate_empno():
f=open("emp.dat",'rb')
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:
f.close()
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.close()

19
def DISPLAY():
f=open("emp.dat",'rb')
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:
f.close()
return

def DELETE():
en=int(input("Enter the emp no. to delete:"))
flag=0
f1=open("emp.dat",'rb')
f2=open("tem.dat",'wb')
try:
while True:
a = pickle.load(f1)
if en != a[0]:
pickle.dump(a,f2)
else:
flag=1
except EOFError:
f1.close()
f2.close()
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 Deletion:")
DISPLAY()

OUTPUT:
Enter how many employees3
Enter emp no.10
Enter employee namearun
Enter basic salary12000
Enter emp no.20

20
Enter employee namekumar
Enter basic salary8000
Enter emp no.30
Enter employee nameshyam
Enter basic salary14000
Contents of the file
EMPNO EMPNAME SALARY
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

14. 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 greater than or equal to 80, respectively.
PROGRAM:
import csv
def CREATE():
f=open("student.csv",'w',newline="")
writer=csv.writer(f,delimiter=',')
while True:
rol=int(input("Enter the rollno:"))
name=input("Enter the name:")
sec=input("Enter the section:")
avg=int(input("Enter the Avg marks:"))
rec=[rol,name,sec,avg]
writer.writerow(rec)
ch=input("press any key to continue?N to exit\n")
if ch in 'nN':
break
f.close()

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

21
def SHOW2():
f=open("student.csv",'r',newline='')
robj=csv.reader(f,delimiter=',')
for a in robj:
if int(a[3]) >=80:
print(a[0],a[1],a[2],a[3],sep='\t')
f.close()

CREATE()
print("All the students details")
SHOW1()
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

22
15. Write a function create() to create password.csv which accepts user id and password.
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”
PROGRAM

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

def SHOW1():
f=open("password.csv",'r',newline='')
robj=csv.reader(f,delimiter=',')
for a in robj:
print(a[0],a[1],sep='\t')
f.close()

def SHOW2():
f=open("password.csv",'r',newline='')
id=(input("Enter the User id to search password:"))
robj=csv.reader(f,delimiter=',')
for a in robj:
if a[0]==id:
print("Password :",a[1])
break
else:
print("User id is not present")
f.close()

CREATE()
SHOW1()
SHOW2()

OUTPUT
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

23
User Name Password
covid2019 corona
Italy 2017 Venice
Enter the User id to search password: Italy 2017
Password : Venice

16. Write a menu driven programs with functions using stack technique. Accept N integers in a list
called NUM. Write a function push(L) which accepts list as argument and pushes all those numbers
which are divisible by 3 from the list L into a list called only_3, and display after pushes all the values.

Write another function pop to delete each number from the list only_3 and display the popped value.
When the list is empty, display error message 'stack is empty'
1. PUSH
2. POP
3. EXIT

PROGRAM
only_3=[]
def PUSH(L):
for i in L:
if i%3==0:
only_3.append(i)
if only_3==[]:
print("No numbers are divisible by 3")
else:
print("Pushed values which are divisible by 3:",end=' ')
for i in only_3:
print(i,end=' ')

def POP():
print("Poped values are:",end=' ')
while only_3:
print(only_3.pop(), end=' ')
print("Stack is empty")

num=[]
n=int(input("How many numbers?"))
for i in range(n):
num.append(int(input("Enter the number")))
while True:
print("\n1. PUSH\n2. POP\n3. Exit")
ch=int(input("Enter Your choice:"))
if ch==1:
PUSH(num)
elif ch==2:
POP()
elif ch==3:
break
else:
print("Invalid choice")

24
OUTPUT
How many numbers?6
Enter the number1
Enter the number2
Enter the number3
Enter the number4
Enter the number5
Enter the number6

1. PUSH
2. POP
3. Exit
Enter Your choice:1
Pushed values which are divisible by 3: 3 6
1. PUSH
2. POP
3. Exit
Enter Your choice:2
Poped values are: 6 3 Stack is empty

1. PUSH
2. POP
3. Exit
Enter Your choice:

17. Write a menu driven programs with functions using stack technique. Create a dictionary containing
Name and total as key value pairs of 6 students. Write a function push() to Push the name of the student
where the corresponding total is greater than 399 to the list L, and display after pushes all the values.
Write another function POP() to delete each name from the list L and display the popped value. When
the list is empty, display error message 'stack is empty'
1. POP
2. PUSH
3. EXIT
For example:
If the sample content of the dictionary is as follows:
d={"OM":476, "JAI":345, "BOB":489, "ALI":365, "ANU":490, "TOM":482}
The output from the program should be:
TOM ANU BOB OM

PROGRAM
L=[]
def PUSH(d):
for k in d:
if d[k]>=400:
L.append(k)
if L==[]:
print("No one got total greater than 399")
else:
print("students who got total greater than 399",L)

25
def POP():
while L:
print(L.pop(),end=" ")
print("Stack is empty")

d={}
for i in range(2):
name=input("Enter the name:")
tot=int(input("Enter the total:"))
d[name]=tot
print("Given dictionary :")
for i,j in d.items():
print(i,j)

while True:
print("\n1. PUSH\n2. POP\n3. Exit")
ch=int(input("Enter Your choice:"))
if ch==1:
PUSH(d)
elif ch==2:
POP()
elif ch==3:
break
else:
print("Invalid choice")

OUTPUT
Enter the name ram
Enter the total 490
Enter the name ranjith
Enter the total 399
Enter the name rahim
Enter the total 496
Enter the name sam
Enter the total 493
Enter the name anu
Enter the total 390
Enter the name aarthi
Enter the total 499
Given dictionary :
ram 490
ranjith 399
rahim 496
sam 493
anu 390
aarthi 499

1. PUSH
2. POP
3. Exit
Enter Your choice:1

26
students who got total greater than 399 ['ram', 'rahim', 'sam', 'aarthi']

1. PUSH
2. POP
3. Exit
Enter Your choice:2
aarthi sam rahim ram Stack is empty

1. PUSH
2. POP
3. Exit
Enter Your choice:

SQL

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()

27
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)

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

28
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.
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.")

29
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:

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")

30
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")

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)

31
('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

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:

32
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)

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

*****

33

You might also like