12 TH Updated Record Prog 2022-2023

Download as pdf or txt
Download as pdf or txt
You are on page 1of 38

PROGRAM : 1

WRITE A FUNCTION PERFECT() WHICH WILL TAKE A NUMBER AS ITS PARAMETER AND CHECK
WHETHER NUMBER IS PERFECT OR NOT.
'''A number is a perfect number if is equal to sum ofits proper divisors,sum of its positive
divisorsexcluding the number itself.'''
SOURCE CODE
def perfect(num):
divsum=0
for i in range(1,num): if
num%i==0:
divsum+=i
if divsum==num:
print(num,"is perfect")
else: print(num,"not perfect")

perfect(6) perfect(15) OUTPUT


6 is perfect

15 not perfect

1
PROGRAM: 2
DESIGN A FUNCTION COMPOUNDINTEREST() WHICH RECEIVES AMOUNT,TIME AND RATE AS
PARAMETERS AND CALCULATES COMPOUND INTEREST.SET DEFAULT VALUE
0.10 FOR RATE AND 2 FOR TIME.
SOURCECODE
#compound interest (amt*(1+rate/100)^time)-amt
def compoundinterest(amt,time=2,rate=0.10):
print("principal:",amt) print("time:",time)
print("rate:",rate)
x=(1+rate/100)**time
return(amt*x-amt)
#MAIN
amt=float(input("enter the amount")) print("function
using default values") print("compound
interest:",compoundinterest(amt)) print("function using
without default values") ci=compoundinterest(amt,4,0.5)
print("compoundinterest",ci)

2
OUTPUT
enter the amount2000 function
using default values principal:
2000.0
time: 2
rate: 0.1
compound interest: 4.001999999999498 function
using without default values principal: 2000.0
time: 4
rate: 0.5
compoundinterest 40.30100124999922
===================================================================

3
PROGRAM : 3
WRITE A FUNCTION STATISTICS(SEN) WHICH RECEIVES A SENTENCE AS A PARAMETER
AND PRINTS THE STATISTICS LIKE NO OF UPPER,NO OF LOWER, NO OF DIGITS PRESENT IN
SENTENCE.
SOURCE CODE
def statistics(sen):
upper=lower=digit=0 for
ch in sen:
if ch.islower():
lower+=1
elif ch.isupper():
upper+=1
elif ch.isdigit():
digit+=1
print(sen)
print("no of uppercase letters",upper)
print("no of lowercase letters",lower)
print("no of digits",digit) statistics("Time is
GOLD from 22223") OUTPUT
Time is GOLD from 22223 no
of uppercase letters 5 no of
lowercase letters 9 no of
digits 5

4
PROGRAM :4
CREATE A TEXT FILE AND WRITE FEW LINES.NOW READ THE FILE CONTENTS LINE
BY LINE AND DISPLAY EACH WORD SEPARATED BY #. SOURCE CODE
def createfile():
fout=open("myfile.txt","w")
lst=[]
for i in range(2):
line=input("enter sentence")
lst.append(line+'\n')
fout.writelines(lst)
fout.close()
def readfile():
fin=open("myfile.txt","r")
wordslist=[] line=fin.read()
wordslist=line.split()
for word in wordslist:
print(word+"#")
fin.close()
createfile()
readfile()

5
OUTPUT
entersentence"GOD NEVER FIX SITUATIONS "
entersentence"HE USES SITUATIONS TO FIX YOU " GOD#
NEVER#
FIX#
SITUATIONS#
HE#
USES#
SITUATIONS#
TO#
FIX#
YOU#
=====================================================================

6
PROGRAM :5
PROGRAM TO READ CONTENT OF FILE AND DISPLAY TOTAL NUMBER OF VOWELS, CONSONANTS,
LOWERCASE AND UPPERCASE CHARACTERS
SOURCE CODE
fout=open("myfile.txt","w")
lst=[]
for i in range(2):
line=input("enter sentence")
lst.append(line+'\n')
fout.writelines(lst) fout.close()
f = open("myfile.txt") v=0
c=0
u=0
l=0
o=0
data = f.read()
print(data)
vowels=['a','e','i','o','u']

for ch in data:
7
if ch.isalpha():
if ch.lower() in vowels:
v+=1
else:
c+=1
elif ch.isupper():
u+=1

elif ch.islower():
l+=1
elif ch!=' ' and ch!='\n':
o+=1
print("Total Vowels in file :",v)
print("Total Consonants in file n :",c)
print("Total Capital letters in file :",u)
print("Total Small letters in file :",l)
print("Total Other than letters :",o)
f.close()

8
OUTPUT
"GOD NEVER FIX SITUATIONS"
"HE USES SITUATIONS TO FIX YOU "
Total Vowels in file 21
Total Consonants in file n 24
Total Capital letters in file 45
Total Small letters in file 0
Total Other than letters 0
==================================================================

9
PROGRAM :6
PROGRAM TO READ LINE FROM FILE AND WRITE IT TO ANOTHER LINE
EXCEPT FOR THOSE LINE WHICH CONTAINS LETTER 'a'

SOURCE CODE
def createfile():
fout=open("file2.txt","w")
lst=[]
for i in range(6):
line=input("enter sentence")
lst.append(line+'\n')
fout.writelines(lst)
fout.close()
createfile()
f1 = open("file2.txt")
f2 = open("file2copy.txt","w")
for line in f1:
if 'a' not in line:
f2.write(line)
print("## File Copied Successfully! ##") f1.close()
f2.close()

10
print("present contents of file2copy.txt")
f2=open("file2copy.txt")
print(f2.read())
OUTPUT
Content of file2.txt a
quick brown fox one
two three four five
six seven
India is my country
eight nine ten
bye!
## File Copied Successfully! ##
present contents of file2copy.txt one
two three four
five six seven
eight nine ten
bye!
====================================================

11
PROGRAM :7
PROGRAM TO READ CONTENTS OF FILE AND PRINT ONLY FOUR LETTER WORDS PRESENT IN THE FILE
SOURCE CODE
def createfile():
fout=open("file2.txt","w")
lst=[]
for i in range(2):
line=input("enter sentence")
lst.append(line+'\n')
fout.writelines(lst)
fout.close()
createfile()
def wordslen4():
fin=open("file2.txt",'r')
str=fin.read()
wordlist=str.split(' ')
print("4 letter words:")
for w in wordlist:
if len(w)==4:
print(w)
wordslen4()

12
OUTPUT
entersentencecbse changed class xii syllabus
entersentencethis year onwordsits is term wise 4
letter words:
cbse
year
term
================================================================

13
PROGRAM :8
PROGRAM TO READ CONTENTS OF FILE AND DISPLAY THOSE LINES STARTS WITH LOWERCASE
CONSONANT AND ENDS WITH A LOWERCASE VOWEL.
SOURCE CODE
def createfile():
fout=open("file2.txt","w")
lst=[]
for i in range(2):
line=input("enter sentence")
lst.append(line+'\n')
fout.writelines(lst)
fout.close()
createfile()
def wordslen4():
fin=open("file2.txt",'r')
lst=fin.readlines()
print("LINES STARTING WITH LOWERCASE CONSONANT ANDS ENDS WITH LOWERCASE
VOWEL")
for l in lst:
if l[0] not in 'aeiou':
if l[-2] in 'aeiou':
print(l)
wordslen4()
14
OUTPUT
enter sentence cbse has changed its exam pattern
enter sentence this year onwards exam will be conducted term wise

LINES STARTING WITH LOWERCASE CONSONANT ANDS ENDS WITH LOWERCASE VOWEL
this year onwards exam will be conducted term wise
=============================================================

15
PROGRAM :9
PROGRAM TO CREATE A BINARY FILE TO STORE ROLLNO AND NAMESEARCH FOR ROLLNO AND
DISPLAY RECORD IF FOUNDOTHERWISE "ROLL NO. NOT FOUND

SOURCE CODE
import pickle
student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
student.append([roll,name])
ans=input("Add More ?(Y)")
pickle.dump(student,f)
f.close()
f=open('student.dat','rb')
student=[]
while True:
try:
student = pickle.load(f)
except EOFError:
break

16
ans='y'
while ans.lower()=='y':
found=False
r = int(input("Enter Roll number to search :")) for s
in student:
if s[0]==r:
print("## Name is :",s[1], " ##")
found=True
break
if not found:
print("####Sorry! Roll number not found ####") ans=input("Search
more ?(Y) :")
f.close()
#binary file roll num,name give roll number print name

17
OUTPUT
Enter Roll Number :1
Enter Name :Amit Add
More ?(Y)y
Enter Roll Number :2
Enter Name :Jasbir Add
More ?(Y)y
Enter Roll Number :3
Enter Name :Vikral Add
More ?(Y)n
Enter Roll number to search :2 ##
Name is :Jasbir ##
Search more ?(Y) :y
Enter Roll number to search :1 ##
Name is :Amit ##
Search more ?(Y) :y
Enter Roll number to search :4 ####Sorry!
Roll number not found #### Search more
?(Y) :n

18
PROGRAM :10
PROGRAM TO CREATE A BINARY FILE TO STORE ROLLNO, NAME AND MARKS SEARCH FOR ROLLNO
AND UPDATE MARKS IF FOUND OTHERWISE "ROLL NO. NOT FOUND
SOURCE CODE
import os import
pickle student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
marks = int(input("Enter Marks :"))
student.append([roll,name,marks])
ans=input("Add More ?(Y)")
pickle.dump(student,f)
f.close()
f=open('student.dat','rb')
student=[]
while True:
try:
student=pickle.load(f) print(student)
except EOFError:
break
19
ans='y'
while ans.lower()=='y':
found=False
r = int(input("Enter Roll number to update :")) for s
in student:
if s[0]==r:
print("## Name is :",s[1], " ##")
print("## Current Marks is :",s[2]," ##") m =
int(input("Enter new marks :")) s[2]=m
print("## Record Updated ##")
found=True
break
if not found:
print("####Sorry! Roll number not found ####") ans=input("Update
more ?(Y) :")

f.close()
f=open('student.dat',"wb")
pickle.dump(student,f)
20
f.close()
print("updated contents from student .dat")
f=open('student.dat','rb')
while True:
try:
student=[]
student=pickle.load(f)

except EOFError:
break
f.close()
OUTPUT
Enter Roll Number :1
Enter Name :lavanya
Enter Marks :89
Add More ?(Y)y
Enter Roll Number :2
Enter Name :shiva Enter
Marks :34
Add More ?(Y)n [[1,
'lavanya', 89]]
[[1, 'lavanya', 89], [2, 'shiva', 34]]
Enter Roll number to update :2 ##
21
Name is :shiva ##
## Current Marks is : 34 ##
Enter new marks :78 ##
Record Updated ##
Update more ?(Y) :n
updated contents from student .dat [[1,
'lavanya', 89], [2, 'shiva', 78]]

22
PROGRAM :11
PROGRAM TO CREATE A BINARY FILE TO STORE ROLLNO, NAME AND MARKS DELETE A
PARTICULAR STUDENT BY SEARCHING HIS ROLL NUMBER SOURCE CODE
import os import
pickle student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
marks = int(input("Enter Marks :"))
student.append([roll,name,marks])
ans=input("Add More ?(Y)")
pickle.dump(student,f)
f.close()
f=open('student.dat','rb')
student=[]

while True:
23
try:
student=pickle.load(f) except
EOFError:
break
ans='y'
newlist=[]
while ans.lower()=='y':
found=False
r = int(input("Enter Roll number to be deleted :")) for s in
student:
if s[0]==r:
print("## student found ")
print("record deleted")
found=True
else:
newlist.append(s)
if not found:
print("####Sorry! Roll number not found ####") ans=input("Delete
more ?(Y) :")
f.close()

f=open('student.dat',"wb")
24
pickle.dump(newlist,f) f.close()
print("updated contents from student .dat")
f=open('student.dat','rb')
while True:
try:
student=[]
student=pickle.load(f)
print(student)

except EOFError:
break
f.close()
OUTPUT
Enter Roll Number :101
Enter Name :shiva Enter
Marks :456
Add More ?(Y)y
Enter Roll Number :102
Enter Name :kumar Enter
Marks :489
Add More ?(Y)y
Enter Roll Number :103
Enter Name :anish Enter
25
Marks :489
Add More ?(Y)n
[[101, 'shiva', 456], [102, 'kumar', 489], [103, 'anish', 489]]
Enter Roll number to be deleted :102 ##
student found
record deleted Update
more ?(Y) :n
updated contents from student .dat [[101,
'shiva', 456], [103, 'anish', 489]]

26
PROGRAM:12
PROGRAM TO CREATE A CSV FILE TO STORE EMPNO,NAME,SALARY AND SEARCH FOR EMPLOYEE
BASED ON EMPNUMBER
SOURCE CODE
import csv
with open('myfile1.csv',mode='a') as csvfile:
mywriter = csv.writer(csvfile,delimiter=',')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter Employee Number "))
name=input("Enter Employee Name ")
salary=int(input("Enter Employee Salary :"))
mywriter.writerow([eno,name,salary]) print("##
Data Saved... ##")
ans=input("Add More ?")
ans='y'
with open('myfile1.csv',mode='r') as csvfile: myreader =
csv.reader(csvfile,delimiter=',') while ans=='y':
found=False
e = int(input("Enter Employee Number to search :")) for
row in myreader:
if len(row)!=0:
if int(row[0])==e:
print("============================")
27
print("NAME :",row[1])
print("SALARY :",row[2])
found=True
break
if not found:
print("==========================")
print(" EMPNO NOT FOUND")
print("==========================")
ans = input("Search More ? (Y)")

OUTPUT
Enter Employee Number 1 Enter
Employee Name Amit Enter
Employee Salary :90000 ## Data
Saved... ##
Add More ?y
Enter Employee Number 2 Enter
Employee Name Sunil Enter
Employee Salary :80000 ## Data
Saved... ##
Add More ?y
Enter Employee Number 3 Enter
Employee Name Satya Enter
Employee Salary :75000 ## Data
28
Saved... ##
Add More ?n
Enter Employee Number to search :2
============================
NAME : Sunil
SALARY : 80000
Search More ? (Y)y
Enter Employee Number to search :3
============================
NAME : Satya
SALARY : 75000
Search More ? (Y)y
Enter Employee Number to search :4
========================== EMPNO
NOT FOUND
Search More ? (Y)n
=====================================================================

29
PROGRAM :13
CREATE A LIST OF5 INTEGERS PUSH THE NUMBERS WHICH ARE DIVISIBLE BY 5 OR 7 INTO STACK POP
AND DISPLAY THE STACK CONTENTS
SOURCECODE
#STACK INTEGERS
lst=[]
st=[]
top=None
for k in range(5): n=int(input("enter
a number")) lst.append(n)
def push(): for
k in lst:
if k%5==0 or k%7==0:
st.append(k)
top=len(st)-1

30
def pop():
if len(st)==0:
print("underflow")
else:
print("going to delete",st.pop())
top=len(st)-1
def display():
print("stack contents are..") for i
in range(len(st)-1,-1,-1):
print(st[i])
choice='y'
while choice=='y':
print("menu")
print("1. push ")
print("2.pop")
print("3.display")
ch=int(input("enter ur choice")) if
ch==1:
push() elif
ch==2:
pop()
elif ch==3:
31
display()
else:
print("invalid choice")
choice=input("do u want to continue")
OUTPUT:
enter a number13
enter a number25
enter a number21
enter a number28
enter a number15
menu
1. push
2.pop
3.display
enter ur choice1
do u want to continuey
menu
1. push
2.pop
3.display
enter ur choice3 stack
contents are.. 15
28
32
21
25
do u want to continuey
menu
1. push
2.pop
3.display
enter ur choice2
going to delete 15
do u want to continuey
menu
1. p
ush
2.pop
3.display
enter ur choice3 stack
contents are.. 28
21
25
do u want to continuen

33
PROGRAM :14
PROGRAM TO DEMONSTRATE STACK OPERATIONS USING DICTIONARIES
CREATE A DICTIONARY EMPLOYEE WITH EMP NAME AS KEY AND THEIR SALARY AS VALUES. WRITE
FUNCTIONS TO PERFORM FOLLOWING OPERATIONS
(a) PUSH THE NAMES OF THOSE EMPLOYESS INTO STACK WHERE SALARY IS LESS THAN 50000
(b) POP THE ELEMENTS OF THE STACK AND DISPLAY THOSE NAMES
SOURCECODE
stack=[]
emp={}
def push():
for d in emp:
if emp[d]<50000:
stack.append(d)
def pop():
if len(stack)==0:
print("no employees under 50000 salary UNDER FLOW")
else:
print("employee going to delete is",stack.pop())
def display():
for i in range(len(stack)-1,-1,-1):
print("employee name::",stack[i])

34
def createdict():
for i in range(4):
ename=input("enter employee name")
sal=int(input("enter emp salary::"))
emp[ename]=sal
#main
createdict()
push()
print("LIST OF EMPLOYEES LESS THAN 50000 SALARY")
display()
print("\n LIST OF EMPLOYEES LESS THAN 50000 SALARY AFTER POPING")
pop()
print("LIST OF EMPLYEE ")
display()

35
OUTPUT
enter employee nameSASI
enteremp salary::65000 enter
employee nameANISH
enteremp salary::23000
enter employee nameGOUTHAM enteremp
salary::77800
enter employee nameLUCKY
enteremp salary::24000
LIST OF EMPLOYEES LESS THAN 50000 SALARY
employee name:: LUCKY
employee name:: ANISH
LIST OF EMPLOYEES LESS THAN 50000 SALARY AFTER POPING
employee going to delete is LUCKY
LIST OF EMPLYEE
employee name:: ANISH

36
PROGRAM:15
WRITE A PROGRAM TO TAKE LIST OF 5 WORDS
PUSH THOSE WORDS WHICH ARENOT HAVING ANY
VOWELS INTO THE STACK POP AND DISPLAY STACK
CONTENT
SOURCE CODE:
st=[]
def push():
for w in words:
for ch in w:
if ch in 'aeiouAEIOU':
break
else:
st.append(w)
def pop():
if len(st)==0:
print(" UNDER FLOW")
else:
print("\n word going to delete is",st.pop())
def display():
print("stack with words without vowels::")
for i in range(len(st)-1,-1,-1):
print(st[i],end='\t')
words=[]
for i in range(5):
w=input("enter a word")
words.append(w)
push()
display()
pop()
print("stack after pop...")
display()
37
OUTPUT:
enter a wordshy
enter a wordcry
enter a wordworls
enter a wordhai
enter a wordfry
stack with words without vowels::
fry cry shy
word going to delete is fry
stack after pop...
stack with words without vowels::
cry shy

38

You might also like