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

Std12 CSc Record Programs 2025

Students are instructed to print and spiral bind their lab records, ensuring specific formatting for program submissions. They must complete 16 Python programs and 6 SQL programs with outputs, and submit the records on June 2nd, 2025. The document outlines detailed instructions for writing programs, including examples of functions for Fibonacci series, prime numbers, string analysis, and more.
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)
1 views

Std12 CSc Record Programs 2025

Students are instructed to print and spiral bind their lab records, ensuring specific formatting for program submissions. They must complete 16 Python programs and 6 SQL programs with outputs, and submit the records on June 2nd, 2025. The document outlines detailed instructions for writing programs, including examples of functions for Fibonacci series, prime numbers, string analysis, and more.
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/ 28

Dear Students,

NOTE: TAKE PRINTOUT OF THIS FILE FOR LAB OBSERVATION AND DO THE SPIRAL
BINDING. EVERYONE MUST BRING THE SPIRAL BINDING FOR THE LAB SESSION
WITHOUT FAIL.

Read ALL the instructions given below, 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. Write 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) SQL: Write output in pencil at left side, remaining including table write at right side

F)Before submitting the record, check whether the following are completed,
1. Sixteen python programs with output and 6 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 numbers

SUBMIT THE RECORD ON THE REOPENING DAY - JUNE 2nd Monday 2025
NAME: CLASS: XII SEC: F
CHETTINAD VIDYASHRAM
STD XII – COMPUTER SCIENCE
RECORD PROGRAMS (2025)

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")
OUTPUT:
1. Fibonacci series
2. Prime numbers
3. Exit
Enter your Choice(1 to 3)...
1
How many terms?5
Fibonacci sequence:
0
1
1
2
3

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:
2
3
5
7

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

2. Write a function that accept a multiword string as argument find and print the number of
occurrence and percentage 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=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
s=len(s)
print("Number of alphabets:",al,"and its % of occurrence:",round((al*100/s),2))
print("Number of uppercase letters:",uc,"and its % of occurrence:",round((uc*100/s),2))
print("Number of lowercase letters:",lc,"and its % of occurrence:",round((lc*100/s),2))
print("Number of digits:",di,"and its % of occurrence:",round((di*100/s),2))
print("Number of spaces:",sp,"and its % of occurrence:",round((sp*100/s),2))
print("Number of special characters:",sc,"and its % of occurrence:",round((sc*100/s),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 occurrence: 64.29
Number of uppercase letters: 8 and its % of occurrence: 28.57
Number of lowercase letters: 10 and its % of occurrence: 35.71
Number of digits: 2 and its % of occurrence: 7.14
Number of spaces: 6 and its % of occurrence: 21.43
Number of special characters: 2 and its % of occurrence: 7.14

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

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("Number of palindrome strings:",p)
print("Number of vowel strings:",v)
print("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

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

5. 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
THIRUVANANTHAPURAM
GOA
PUNE
VIJAYAWADA
Longest string is: THIRUVANANTHAPURAM
Shortest string is: GOA
Greatest string is: VIJAYAWADA
Smallest string is: CHENNAI
6. Write a program to create a dictionary with salesman code as key and a tuple with elements
like name, product type, sales amount and commission for N salesmen. Also write a function to display the
result in the format given below.
Commission calculation:

Product Type % of commission on Sales Amount


Medicine 20%
Food 25%
Garments 18%
Other products 15%
Result should be printed as follows
------------------------------------------------------------------------------------------
S.No Code Name Prod. Type Sales AmountCommission
------------------------------------------------------------------------------------------
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 Sales 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\tSales 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
#main prg
d={}
n=int(input("How many salesmen?"))
ACCEPT(d,n)
PRINT(d,n)

OUTPUT:
How many salesmen?4
Enter salesman code:101
Enter name:CROCIN
Enter Product Type:MEDICINE
Enter Sales Amount:300
Enter salesman code:102
Enter name:SUGAR
Enter Product Type:FOOD
Enter Sales Amount:650
Enter salesman code:103
Enter name:T-SHIRT
Enter Product Type:GARMENT
Enter Sales Amount:2250
Enter salesman code:104
Enter name:PONDS
Enter Product Type:COSMETIC
Enter Sales Amount:525
------------------------------------------------------------------------------------------
S.No Code Name Prod Type Sales 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

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

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

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

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

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

9. 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")
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 occurrence
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

10. 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 CreateEmp():
f=open("emp.dat",'wb')
n=int(input("Enter how many employees"))
for i in range(n):
eno=int(input("Enter emp no."))
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()

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

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

11. A binary file “emp.dat” has record format {empno: [ empname,salary] }. Write a user defined
function CreateEmp() to input data for a record and add to emp.dat . Also write a function
copy_new() that copies all records whose salary is greater than 10000 from emp.dat to
new_emp.dat. Display the file contents of both emp.dat and new_emp.dat using DISPLAY()
function.

PROGRAM:
import pickle
def CreateEmp():
f=open("emp.dat",'wb')
n=int(input("Enter how many employees"))
for i in range(n):
d={}
eno=int(input("Enter Employee number"))
ename=input("Enter employee name")
salary=int(input("Enter basic salary"))
d[eno]=[ename,salary]
pickle.dump(d,f)
f.close()

def DISPLAY(fname):
f=open(fname,'rb')
print("\nEMPNO\tEMPNAME\tSALARY")
try:
while True:
a = pickle.load(f)
for i,j in a.items():
print(i,j[0],j[1],sep='\t')
except EOFError:
f.close()

def copy_new():
flag=0
f=open("emp.dat",'rb')
f2=open("new_emp.dat",'wb')
try:
while True:
a = pickle.load(f)
for i in a.keys():
if a[i][1]>10000:
pickle.dump(a,f2)
flag=1
except EOFError:
f.close()
f2.close()
if flag==0:
print("\nNo employees got salary > 10000!!")

CreateEmp()
print("\nContents of the emp.dat")
DISPLAY("emp.dat")
copy_new()
print("\ncontents of New file new_emp.dat")
DISPLAY("new_emp.dat")

OUTPUT:
Enter how many employees3
Enter Employee number101
Enter employee nameAKASH
Enter basic salary15000
Enter Employee number102
Enter employee nameANIRUDH
Enter basic salary9500
Enter Employee number103
Enter employee nameARUN
Enter basic salary12000

Contents of the emp.dat

EMPNO EMPNAME SALARY


101 AKASH 15000
102 ANIRUDH 9500
103 ARUN 12000

contents of New file new_emp.dat

EMPNO EMPNAME SALARY


101 AKASH 15000
103 ARUN 12000

12. Write a function create() to creates student.dat which has a record structure as list [enroll, name,
total] and display the details. Write another function UPDATE() which input the enroll and update
the total.

PROGRAM:
import pickle as p
def create():
f=open("student.dat",'wb')
n=int(input("How many students?"))
for i in range(n):
enr=int(input("\nEnter enroll"))
name=input("Enter name")
total=int(input("Enter total"))
a=[enr,name,total]
p.dump(a,f)
f.close()

def display():
f=open("student.dat",'rb')
print("\nEnroll Name Total\n")
try:
while True:
a=p.load(f)
print(a[0],a[1],a[2])
except EOFError:
f.close()

def UPDATE():
f=open("student.dat",'rb')
en=int(input("\nEnter the enroll to change the total"))
try:
newlist=[] #list for storing all the records
flag=0
while True:
a=p.load(f)
if a[0] == en:
t=int(input("\nEnter the new total"))
a[2]=t
flag=1
newlist.append(a)
except EOFError:
f.close()
if flag==0:
print("No students has the enroll : ", x)

# writing newlist i.e., updated records back into student.dat


f=open("student.dat",'wb')
for i in newlist:
p.dump(i,f)
f.close()
create()
display()
UPDATE()
print("\nDetails after updation\n")
display()

OUTPUT:
How many students?2

Enter enroll501
Enter nameHARI
Enter total490
Enter enroll101
Enter namePRAVEEN
Enter total480

Enroll Name Total

501 HARI 490


101 PRAVEEN 480

Enter the enroll to change the total101

Enter the new total495

Details after updation

Enroll Name Total

501 HARI 490


101 PRAVEEN 495

13. 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)
n=int(input("How many students?"))
for i in range(n):
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)
f.close()

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

def show2():
f=open("student.csv",'r')
reader=csv.reader(f)
print("\nRollno Name Section Avg_marks")
for a in reader: # iterate from second row
if int(a[3]) >=80: # int() fn is given as the data stored always 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:
How many students?3
Enter the rollno:101
Enter the name:PAVI
Enter the section:B
Enter the Avg marks:90
Enter the rollno:102
Enter the name:CIBI
Enter the section:A
Enter the Avg marks:60
Enter the rollno:103
Enter the name:KAVI
Enter the section:C
Enter the Avg marks:80
All the students details

Rollno Name Section Avg_marks


101 PAVI B 90
102 CIBI A 60
103 KAVI C 80

Students who have got average >=80

Rollno Name Section Avg_marks


101 PAVI B 90
103 KAVI C 80

14. 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="")
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 the password:"))
reader=csv.reader(f)
for a in reader:
if a[0]==id:
print("Password :",a[1])
break
else:
print("User id is not present")
f.close()

create()
show()
show2()

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

15. Write a menu driven program 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. POP
2. PUSH
3. EXIT

PROGRAM:
def PUSH(L):
for i in L:
if i%3==0:
only_3.append(i)
#display the list only_3
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("Popped values are:",end=' ')
while only_3: #empty list returns false
print(only_3.pop(), end=' ')
print("Stack is empty")

num=[]
only_3=[]
n=int(input("How many numbers?"))
for i in range(n):
a=int(input("Enter the number"))
num.append(a)
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")

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
Popped values are: 6 3 Stack is empty

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

16. Write a menu driven program 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:
def PUSH():
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)

def POP():
while True:
if L!=[]:
print(L.pop(),end=" ")
else:
break
print("Stack is empty")
d={}
L=[]
for i in range(6):
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()
elif ch==2:
POP()
elif ch==3:
break
else:
print("Invalid choice")

OUTPUT:
Enter the nameRam
Enter the total490
Enter the nameRanjith
Enter the total399
Enter the nameRahim
Enter the total496
Enter the nameSam
Enter the total493
Enter the nameAnu
Enter the total390
Enter the nameAarthi
Enter the total499
Given dictionary :
Ram 490
Ranjith 399
Rahim 496
Sam 493
Anu 390
Aarthi 499

1. PUSH
2. POP
3. Exit
Enter Your choice:1
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:3

SQL
I. Write SQL commands for questions 1 to 6 using the given STUDENT table.
-------------------------------------------------------------------------------------------------------------------
Roll Name Stipend Stream Avgmark Grade
-------------------------------------------------------------------------------------------------------------------
101 Karan 400 Medical 78.5 B
102 Divakar 450 Commerce 89.2 A
103 Divya 300 Commerce 68.6 C
104 Arun 450 Medical 85.5 A
105 Sophy 600 Biology 90.3 A
-------------------------------------------------------------------------------------------------------------------
1. To create the table STUDENT with the following constraints:
Attribute Data Type Size Constraint
Roll int 5 primary key
Name varchar 20
Stipend int 4
Stream varchar 10
Avgmark float 6,2
Grade char 1
2. Add the above given tuples.
3. To display the details of medical stream student from the student table.
4. To display stream and number of students in each stream of the given table student.
5. To display the name and grade whose avgmark is above 85.
6. To increase the stipend by 200 whose grade is A.

Answers:
1. create table student (roll int(5) primary key, name varchar(20),stipend int(4), stream varchar(10),
avgmark float(6,2), grade char);
2. insert into student values(101,”Karan”,400,”Medical”, 78.5,’B’);
(insert the remaining records using the same insert query format)
3. select * from STUDENT where STREAM=”Medical”;
4. select STREAM, count(*) from STUDENT group by STREAM;
5. select NAME, GRADE from STUDENT where AVGMARK>85;
6. update student set stipend=stipend+200 where grade=’A’;
II. Write SQL commands for questions 1 to 6 using the given SALES table.
-------------------------------------------------------------------------------------------------------------------
NAME PRODUCT P_CODE QTY_TAR PRICE COMMISSION
-------------------------------------------------------------------------------------------------------------------
Santhosh Lux S002B 50 15.35 120
Praveen Harpic T098C 20 40.25 150
Kumar Britannia G045E 20 11.25 100
Arjun Glaxo G045E 30 67.85 150
Jacob Hamam S002B 40 11.50 200
-------------------------------------------------------------------------------------------------------------------
1. To create the table SALES with the following constraints:
Attribute Data Type Size Constraint
Name varchar 20 Not Null
Product varchar 15
P_code char 10
Qty_tar int 2
Price float 7, 2
Commission int 5
2. Add the above given tuples.
3. To display all the records of whose QTY_TAR is more than 35 in ascending order of product.
4. To display the name and product where the product is Britannia and the commission>=100.
5. To display the P_CODE, number of records for each P_CODE from the table sales.
6. To delete the record whose commission is 150

Answers:
1. create table sales (Name varchar(20) not null, Product varchar(15), P_code char(10), Qty_tar
int(2), Price float(7,2), Commission int(5));
2. insert into sales values(”Santhosh”, ”Lux”, ‘S002B’, 50,15.35,120);
(Insert the remaining records using the same insert query format)
3. select * from SALES where QTY_TAR>35 order by PRODUCT;
4. select NAME, PRODUCT from SALES where PRODUCT =’Britannia” and
COMMISSION>=100;
5. select P_CODE, count(*) from SALES group by P_CODE;
6. delete from sales where commission=150;

III. Write SQL commands for questions 1 to 6 using the given MOVIE table.
-------------------------------------------------------------------------------------------------------------------
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.25
Down Periscope Comedy PG13 Stone 6 43.25
Conair Action G Nicholas 3 55.25
-------------------------------------------------------------------------------------------------------------------
1. To create the table MOVIE with the following constraints:
Attribute Data Type Size Constraint
Title varchar 20 Not Null
Type varchar 10
Rating char 10
Stars varchar 20
Qty int 3
Price float 5, 2
2. Add the above given tuples.
3. To display all the details arranged by ascending order of title.
4. To display all the stars whose name starts with ‘S’.
5. To display Rating and number of records for each Rating.
6. To change the value of quantity as 10 for the movie type ‘comedy’.

Answers:
1. create table movie (title varchar(20) not null, type varchar(10), rating char(10), stars varchar(20),
qty int(3),price float(5,2));
2. insert into movie values(“Liar Liar”, ” Comedy”,”PG13”,”Jim Carre”,5,25.35);
(Insert the remaining records using the same insert query format)
3. select * from MOVIE order by TITLE ;
4. select stars from MOVIE where STARS like ‘S%’;
5. select RATING, count(*) from MOVIE group by RATING;
6. update movie set qty=10 where type=’comedy’;

IV. Write SQL commands for questions 1 to 6 using the given LIBRARY table.
-------------------------------------------------------------------------------------------------------------------
BID TITLE AUTHOR TYPE PUB QTY DATE_OF_ISSUE
-------------------------------------------------------------------------------------------------------------------
101 Data structure Lipchutz DS McGraw 4 2019-01-05
102 Advanced Pascal Schildt PROG BPB 5 2019-02-16
103 Mastering C++ Gurewich PROG PHI 3 2019-03-22
104 Mastering Window Cowart OS BPB 6 2019-01-28
105 Network Guide Freed NET Zpress 5 2019-02-20
------------------------------------------------------------------------------------------------------------------------
1. To create the table LIBRARY with the following constraints:
Attribute Data Type Size Constraint
Bid int 5 Primary key
Title varchar 25 Not Null
Author varchar 20
Type char 10
Pub varchar 10
Qty int 4
Date_of_issue date date
2. Add the above given tuples.
3. To display the number of books published by BPB.
4. To display the details of the books whose issued date is after January 2019.
5. To display the pub and average quantity of each publisher.
6. To delete the record whose type is PROG.

Answers:
1. create table library (bid int(5) primary key, title varchar(25) not null ,author varchar(20), type
char(10), pub varchar(10), qty int(4), date_of_issue date);
2. insert into library values(101,”Data structure”,”Lipchutz”,”DS”,”McGraw”,4,“2019-01-05”);
(Insert the remaining records using the same insert query format)
3. select count(*) from library where PUB =’BPB’;
4. select * from library where date_of_issue >’2019-01-31’;
5. select pub, avg(qty) from library group by pub;
6. delete from library where type=’PROG’;

V. Using Python connectivity with SQL, write a function CREATE () to create N patients records and
display() to display all the records. The database name is ‘project’ and a table name is ‘hospital’ which has
3 attributes – pname – char 30, pid int and fees float 9,2.
Assume the following for python-Database connectivity :
Host: localhost, user: root, password: root

PROGRAM:
import mysql.connector
import time
con=mysql.connector.connect(host='localhost', user='root', password='root', charset='utf8')
cur=con.cursor()
#cur.execute("drop database project")
cur.execute("create database project")
cur.execute("use project")
cur.execute("create table hospital(pname char(30), pid int, fees float(9,2) )")

def create():
n=int(input("How many patients"))
for i in range(n):
pn=input("Enter name")
pid=int(input("Enter ID"))
fees=float(input("Enter fees"))
cur.execute("insert into hospital values('%s',%s,%s )" %(pn,pid,fees) )
con.commit()
def display():
cur.execute("select * from hospital")
print("Name\tID\tFees")
for x in cur:
print(x[0], x[1], x[2], sep='\t')
create()
display()

OUTPUT :

How many patients 2


Enter name Anirudh
Enter ID 708
Enter fees 50000.75
Enter name Rakesh
Enter ID 805
Enter fees 100000
Name ID Fees
Anirudh 708 50000.75
Rakesh 805 100000.0

VI. Using Python connectivity with SQL, write a function CREATE() to create N Patients records and
display the details. Write a function delete() to input a patient ID and delete the given patient ID details.
The database name is ‘project’ and a table name is ‘hospital’ which has 3 attributes –pname – char 30 , pid
int and fees float 9,2 .
Assume the following for python-Database connectivity :
Host: localhost, user: root, password:'root'

PROGRAM:
import mysql.connector
import time
con=mysql.connector.connect(host='localhost',user='root',password='root',charset='utf8' )
cur=con.cursor()
#cur.execute("drop database project")
cur.execute("create database project")
cur.execute("use project")
cur.execute("create table hospital(pname char(30), pid int , fees float(9,2) )")

def create():
n=int(input("How many patients"))
for i in range(n):
pn=input("Enter name")
id=int(input("Enter ID"))
fees=float(input("Enter fees"))
cur.execute("insert into hospital values( '%s',%s,%s )"%(pn,id,fees) )
con.commit()
cur.execute("select * from hospital")
#display the details using fetchall()
a=cur.fetchall()
print("Name\tID\tFees")
for i in a:
print(i[0], i[1], i[2], sep='\t')
def delete():
id=int(input("Enter the ID to delete"))
cur.execute('delete from hospital where pid={}'.format(id))
con.commit()
# display the records after delete
cur.execute("select * from hospital")
print("Name\tID\tFees")
for x in cur:
print(x[0],x[1],x[2],sep='\t')

create()
delete()

OUTPUT
How many patients 3
Enter name ANAND
Enter ID 101
Enter fees 1000
Enter name ARUL
Enter ID 102
Enter fees 2000
Enter name ANIL
Enter ID 502
Enter fees 3000
Name ID Fees
ANAND 101 1000.0
ARUL 102 2000.0
ANIL 502 3000.0
Enter the ID to delete 102
Name ID Fees
ANAND 101 1000.0
ANIL 502 3000.0

***********

You might also like