[go: up one dir, main page]

0% found this document useful (0 votes)
21 views37 pages

XII CSC RecordProgram2024

Uploaded by

psb6950
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)
21 views37 pages

XII CSC RecordProgram2024

Uploaded by

psb6950
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/ 37

CHETTINAD VIDYASHRAM

STD XII – COMPUTER SCIENCE


RECORD PROGRAMS (2024)
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,end=' ')
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,end=' ')
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:
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 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=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 occurrence:",round((al*100/l),2))
print("Number of uppercase letters:",uc,"and its % of occurrence:",round((uc*100/l),2))
print("Number of lowercase letters:",lc,"and its % of occurrence:",round((lc*100/l),2))
print("Number of digits:",di,"and its % of occurrence:",round((di*100/l),2))
print("Number of spaces:",sp,"and its % of occurrence:",round((sp*100/l),2))
print("Number of special characters:",sc,"and its % of occurrence:",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 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 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
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]

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
THIRUVANANTHAPURAM
GOA
PUNE
VIJAYAWADA
Longest string is: THIRUVANANTHAPURAM
Shortest string is: GOA
Greatest string is: VIJAYAWADA
Smallest string is: CHENNAI

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 in the format given below. Commission is calculated as per the following
criteria:
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)

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 Product Type: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:")
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={}
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:ARGENTINA
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', 'ARGENTINA', 689], 'HOCKEY': ['SREEJESH PR', 'INDIA', 756],
'CRICKET': ['DHONI', 'INDIA', 789]}
----------------------------------------------------------------------------------------------------

Records in Ascending order of Game:


CRICKET ['DHONI', 'INDIA', 789]
FOOTBALL ['MESSI', 'ARGENTINA', 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
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:ARGENTINA
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', 'ARGENTINA', 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', 'ARGENTINA', 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 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()

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

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)
f.write('\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 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
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():
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():
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 employees: 3
Enter Emp No.: 10
Enter Employee Name: ARUN
Enter Basic Salary: 12000
Enter Emp No.: 20
Enter Employee Name: KUMAR
Enter Basic Salary: 9000
Enter Emp No.: 30
Enter Employee Name: SHYAM
Enter Basic Salary: 13000

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

def DISPLAY(fname):
with open(fname,'rb') as f:
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:
return
def copy_new():
flag=0
with open("emp.dat",'rb') as f, open("new_emp.dat",'wb') as f2:
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!!")
return

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

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

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="")
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)
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 password:italy2017
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 3from the list L into a list called only_3, and display after
pushing 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:")
for i in range(len(only_3)-1,-1,-1):
print(only_3[i])

def POP():
print("Poped values are:")
while only_3: #empty list returns false
print(only_3.pop())
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:
6
3

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

17. 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 pushing 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("Noone got total greater than 399")
else:
print("students who got total greater than 399 are",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 :")
print(d)
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 name OM
Enter the total 476
Enter the name JAI
Enter the total 345
Enter the name BOB
Enter the total 489
Enter the name ALI
Enter the total 365
Enter the name ANU
Enter the total 490
Enter the name TOM
Enter the total 482
Given dictionary :
{'OM': 476, 'JAI': 345, 'BOB': 489, 'ALI': 365, 'ANU': 490, 'TOM': 482}

1. PUSH
2. POP
3. Exit
Enter Your choice:1
students who got total greater than 399 are ['OM', 'BOB', 'ANU', 'TOM']

1. PUSH
2. POP
3. Exit
Enter Your choice:2
TOM ANU BOB OM Stack is empty

1. PUSH
2. POP
3. Exit
Enter Your choice:3
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()
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
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 into sales values('Santhosh','Lux',50,15.35,120)")
cur.execute("insert into sales values('Praveen','Harpic',25,40.25,150)")
cur.execute("insert into sales values('Kumar','Britannia',20,11.25,100)")
cur.execute("insert into sales values('Arjun','Glaxo',30,67.85,150)")
cur.execute("insert 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:
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 varchar(20) primary key, type varchar(10),
rating varchar(15), stars varchar(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)
('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:
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

*****

You might also like