[go: up one dir, main page]

0% found this document useful (0 votes)
22 views21 pages

Record Programs

The document contains examples of Python programs and functions to perform operations on lists, tuples, strings and dictionaries. It includes problems on list manipulation, searching elements, capitalizing words, unique values, tuples, character deletion, substring occurrence and random number generation.

Uploaded by

xx id
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)
22 views21 pages

Record Programs

The document contains examples of Python programs and functions to perform operations on lists, tuples, strings and dictionaries. It includes problems on list manipulation, searching elements, capitalizing words, unique values, tuples, character deletion, substring occurrence and random number generation.

Uploaded by

xx id
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/ 21

CLASS 12 RECORD PROBLEMS – TERM I - KEY

LIST-SWAP Date : 09/04/21


1) A list Num contains the following elements
3,25,13,6,35,8,14,45
Write a program using function SWAP() that takes in a list as a parameter and
swaps the content with the next value divisible by 5 so that the resultant list will
look like:
25,3,13,35,6,8,45,14

def SWAP(lst):
for i in range(len(lst)-1):
if lst[i+1]%5==0:
lst[i],lst[i+1]=lst[i+1],lst[i]
for i in range(len(lst)):
print(lst[i],end=' ')
lst=[]
while True:
x=int(input("1.List Creation 2.Swap values 3.Exit"))
if x==1:
lst=eval(input("Enter a list"))
elif x==2:
SWAP(lst)
elif x==3:
break
else:
print("Invalid Code")
1.List Creation 2.Swap values 3.Exit1
Enter a list[32,35,45,6,8,10,15,12]
1.List Creation 2.Swap values 3.Exit2
35 45 32 6 10 15 8 12
1.List Creation 2.Swap values 3.Exit1
Enter a list[3,25,13,6,35,8,14,45]
1.List Creation 2.Swap values 3.Exit2
25 3 13 35 6 8 45 14
1.List Creation 2.Swap values 3.Exit3

LIST – SEARCH Date : 09/06/21


2) Write a python program that uses a function SEARCH() which takes a list as
parameter and searches an element in a list and displays the position of the
element present in the list and its frequency .
Note: [List and search element should be entered by user]

def Search(lst):
x=int(input("Enter the element you want to search"))
found=False
for i in range(len(lst)):
if lst[i]==x:
found=True
print("Position ",i,end=' ')
if found:
print("Frequency",lst.count(x))
else:
print("Element not found")
lst=[]
while True:
x=int(input("1.List Creation 2.Search value 3.Exit"))
if x==1:
lst=eval(input("Enter an integer"))
elif x==2:
Search(lst)
elif x==3:
break
else:
print("Invalid Code")

1.List Creation 2.Search value 3.Exit1


Enter a list[2,1,5,3,7,4,3,6,1,3,2,1,6,7,4,5,1]
1.List Creation 2.Search value 3.Exit2
Enter the element you want to search5
Position 2 Position 15 Frequency 2
1.List Creation 2.Search value 3.Exit3

STRING-CAPITALIZE Date : 11/06/21


3) Write a python program that uses the function CAPITALIZE() that takes in a
string as a parameter and capitalizes the first and last letters of each word in a
given string.

def CAPITALIZE(String):
String=String.title()
lst=String.split()
String2=''
for i in lst:
String2=String2+i[:-1]+i[-1].upper()+' '
print(String2)
String=" "
while True:
x=int(input("1.String Creation 2.Capitalize 3.Exit"))
if x==1:
String=input("Enter String")
elif x==2:
CAPITALIZE(String)
elif x==3:
break
else:
print("Invalid Code")
1.String Creation 2.Capitalize 3.Exit1
Enter Stringsky is high
1.String Creation 2.Capitalize 3.Exit2
SkY IS HigH
1.String Creation 2.Capitalize 3.Exit1
Enter StringTo err is human
1.String Creation 2.Capitalize 3.Exit2
TO ErR IS HumaN
1.String Creation 2.Capitalize 3.Exit3

LIST – UNIQUE VALUES Date:14/06/21


4) Write a program using function called UNIQUE(List) that gets unique values
from a list.

def Unique(lst):
i=0
j=i+1
while i < len(lst):
j=i+1
while j<len(lst):
if lst[i]==lst[j]:
lst.pop(j)
else:
j+=1
i+=1
print(lst)
lst=[]
while True:
x=int(input("1.List Creation 2.Unique values 3.Exit"))
if x==1:
lst=eval(input("Enter elements"))
elif x==2:
Unique(lst)
elif x==3:
break
else:
print("Invalid Code")

1.List Creation 2.Unique values 3.Exit1


Enter elements[2,33,4,55,1,33,7,8,33,6,4,1]
1.List Creation 2.Unique values 3.Exit2
[2, 33, 4, 55, 1, 7, 8, 6]
1.List Creation 2.Unique values 3.Exit1
Enter elements[2,1,3,4,67,8,2,1,3,67,8]
1.List Creation 2.Unique values 3.Exit2
[2, 1, 3, 4, 67, 8]
1.List Creation 2.Unique values 3.Exit3

DICTIONARY – CREATE AND UPDATE Date:16/06/21


5) Write a python script to print a dictionary where the keys are numbers between 1
and 15(both included) and the values are square of keys.
Sample Dictionary:
{1:1,2:4,3:9,4:16…15:225}
Also write a function SEARCH() that takes in the dictionary D as parameter and
searches for a particular key, if found returns the corresponding value, if not
found , an error message will be displayed.

def Search(d):
x=int(input("Enter a key value to search"))
if x in d.keys():
print("Key ",x," is found, the value is ",d.get(x))
else:
print("Key not found")
d={}
for i in range(1,16):
d[i]=i*i
print(d)
while True:
x=int(input("1.Search for a value 2.Exit"))
if x==1:
Search(d)
elif x==2:
break
else:
print("Invalid Code")

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144,
13: 169, 14: 196, 15: 225}
1.Search for a value 2.Exit1
Enter a key value to search2
Key 2 is found, the value is 4
1.Search for a value 2.Exit1
Enter a key value to search18
Key not found
1.Search for a value 2.Exit2

TUPLE Date:23/06/21
6) Write a program using a function BUILD() to input any values for two tuples. Also
print them, interchange them and compare them with any two relational
operators.

def BUILD():
global t1,t2
t1=eval(input("Enter tuple1"))
t2=eval(input("Enter tuple2"))
def PIC():
global t1,t2
print("Printing tuples")
print(t1)
print(t2)
print("Interchanging tuples")
t1,t2=t2,t1
print(t1)
print(t2)
print("Comparing tuples")
print(t1,t2)
print("t1>t2")
print(t1>t2)
print("t1<t2")
print(t1<t2)
print("t1==t2")
print(t1==t2)
print("t1!=t2")
print(t1!=t2)

t1=()
t2=()
while True:
x=int(input("1. Create Tuples 2.Print,Interchange and Compare tuples 3.Exit"))
if x==1:
BUILD()
elif x==2:
PIC()
elif x==3:
break
else:
print("Invalid Code")

Output:

1. Create Tuples 2.Print,Interchange and Compare tuples 3.Exit1


Enter tuple1(33.5,99.5,23,'cat','dog',[14,23.5,'face'])
Enter tuple2(34.5,98,22,'abacus','deer',[13,22.5,'book'])
1. Create Tuples 2.Print,Interchange and Compare tuples 3.Exit2
Printing tuples
(33.5, 99.5, 23, 'cat', 'dog', [14, 23.5, 'face'])
(34.5, 98, 22, 'abacus', 'deer', [13, 22.5, 'book'])
Interchanging tuples
(34.5, 98, 22, 'abacus', 'deer', [13, 22.5, 'book'])
(33.5, 99.5, 23, 'cat', 'dog', [14, 23.5, 'face'])
Comparing tuples
(34.5, 98, 22, 'abacus', 'deer', [13, 22.5, 'book']) (33.5, 99.5, 23, 'cat', 'dog', [14,
23.5, 'face'])
t1>t2
True
t1<t2
False
t1==t2
False
t1!=t2
True
1. Create Tuples 2.Print,Interchange and Compare tuples 3.Exit3

STRING-DELETE_CHAR Date:30/06/21
7) Write a program that uses the function Deletechar() which takes two parameters
– one is a string and the other is a character. The function should create a new
string after deleting all occurrences of the character from the string and return the
new string.

def Deletechar(String,Char):
String=String.replace(Char,'')
print(String)
String=" "
while True:
x=int(input("1.String Creation 2.Delete the character 3.Exit"))
if x==1:
String=input("Enter String")
elif x==2:
Char=input("Enter a character to remove from string")
Deletechar(String,Char)
elif x==3:
break
else:
print("Invalid Code")
1.String Creation 2.Delete the character 3.Exit1
Enter StringHardv Wvorkv Pavysv
1.String Creation 2.Delete the character 3.Exit2
Enter a character to remove from stringv
Hard Work Pays
1.String Creation 2.Delete the character 3.Exit3

STRING-OCCURENCE Date:07/07/21
8) Write a program using a function OCCUR() to print the number of occurrences of
a substring into a line using find() function.

def Occur(String,Substring):
Count=String.count(Substring)
print(Count)
String=" "
while True:
x=int(input("1.String Creation 2.Occurence of Substring 3.Exit"))
if x==1:
String=input("Enter String")
elif x==2:
Substring=input("Enter substring to find occurences from string")
Occur(String,Substring)
elif x==3:
break
else:
print("Invalid Code")

1.String Creation 2.Occurence of Substring 3.Exit1


Enter Stringshe sells sea shells at the sea shore
1.String Creation 2.Occurence of Substring 3.Exit2
Enter substring to find occurences from stringsea
2
1.String Creation 2.Occurence of Substring 3.Exit1
Enter StringThe rain in Spain stays mainly in the plain
1.String Creation 2.Occurence of Substring 3.Exit2
Enter substring to find occurences from stringain
4
1.String Creation 2.Occurence of Substring 3.Exit2
Enter substring to find occurences from stringains
0
1.String Creation 2.Occurence of Substring 3.Exit3

RANDOM
9) Random Number generator. Date:21/07/21

Write a program to play a dice game that generates 3 random numbers


between 1 and 6. If all the three random numbers are equal, the score is
increased by 50 points and the program quits.
if any two random numbers are equal, then score is increased by 25
points otherwise, score is increased by 10 points.
The program runs as long as the user wants to continue.

from random import *


score=0
while True:
a=randint(1,6)
b=randint(1,6)
c=randint(1,6)
print("a=",a,"b=",b,"c=",c)
if a==b==c:
score+=50
print("adding 50")
break
elif a==b or b==c or a==c :
score+=25
print("adding 25")
else:
score+=10
print("adding 10")
print("The score is ",score)
ans=input("Continue(y/n)?")
if ans=='n' or ans=='N':
break

a= 5 b= 5 c= 6
adding 25
The score is 25
Continue(y/n)?y
a= 2 b= 4 c= 2
adding 25
The score is 50
Continue(y/n)?y
a= 4 b= 3 c= 3
adding 25
The score is 75
Continue(y/n)?y
a= 5 b= 1 c= 3
adding 10
The score is 85
Continue(y/n)?y
a= 6 b= 4 c= 6
adding 25
The score is 110
Continue(y/n)?y
a= 5 b= 5 c= 5
adding 50

TEXT FILE-# Date:28/07/21


10) Read a text file line by line and display each word separated by a
#.
def hash():
with open('conf.txt') as file:
s=file.readline()
while(s):
i=s.split()
print('#'.join(i))
s=file.readline()
hash()

conf.txt

I have confidence in sunshine


I have confidence in rain
I have confidence that spring will come again
I have confidence in me

Output:
I#have#confidence#in#sunshine#I#have#confidence#in#rain#I#have#confid
ence#that#spring#will#come#again#I#have#confidence#in#me#

TEXT FILE-DIFFERENT CHARACTERS Date:09/08/21


11) Read a text file and display the number of vowels /consonants /
uppercase / lowercase characters in the file.

def VCLU():
V=0
C=0
L=0
U=0
with open('vowels.txt') as file:
s=file.read()
for i in s:
if i in 'aeiouAEIOU':V+=1
if not i in 'aeiouAEIOU':C+=1
if i.islower():L+=1
if i.isupper(): U+=1
print("Vowels",V,"Consonants",C,"Lowercase letters",L,"Uppercase letters",U)

VCLU()

Vowels.txt
Every Moment Is a Fresh Beginning

Output
Vowels 10 Consonants 23 Lowercase letters 23 Uppercase letters 5

TEXT FILE – REMOVAL Date:12/08/21


12) Remove all the lines that contain the character 'a' in a file and
write it to another file.

def Aa():
with open('conf2.txt','r') as In:
with open('temp.txt','w') as out:
s=In.readlines()
l1=[]
for i in s:
if 'a' in i or 'A' in i:
out.write(i)
else:
l1.append(i)
with open('conf2.txt','w+') as In:
with open('temp.txt','r') as out:
In.seek(0)
In.write(''.join(l1))
print("\nOriginal file")
In.seek(0)
print(In.read())
print("\nCopied file")
print(out.read())
Aa()

Conf2.txt(before changes)
confidence in sunshine
confidence in rain
confidence that spring will come again
confidence in me

Output
Original file
confidence in sunshine
confidence in me

Copied file
confidence in rain
confidence that spring will come again
BINARY FILE – CREATION AND SEARCH Date:16/08/21
13) Create a binary file with . Search for a given roll number and
display the name, if not found display appropriate message.
import pickle
def Append():
with open('student.dat','ab')as file:
while True:
stud=[]
Rollno=int(input("Enter rollno"))
Name=input("Enter Name")
Marks=eval(input("Enter marks"))
stud=[Rollno,Name,Marks]
pickle.dump(stud,file)
ans=input("Continue(y/n)")
if ans=='n' or ans=='N':
break
def Search():
r=int(input("enter rollno to search"))
found=False
with open('student.dat','rb')as file:
while True:
try:
stud=pickle.load(file)
if stud[0]==r:
print("Name : ",stud[1])
print("Marks: ",stud[2])
found=True
except EOFError :
break
if not found:
print("Sorry, record not found")

while True:
opt=int(input("1.Append 2.Search 3.Exit"))
if opt==1:
Append()
elif opt==2:
Search()
elif opt==3:
break
else:
print("Invalid Code")
Output:
1.Append 2.Search 3.Exit1
Enter rollno1
Enter NameAashini
Enter marks90
Continue(y/n)y
Enter rollno2
Enter NameArchit
Enter marks85.5
Continue(y/n)y
Enter rollno3
Enter NameAthreya
Enter marks90.5
Continue(y/n)n
1.Append 2.Search 3.Exit2
enter rollno to search2
Name : Archit
Marks: 85.5
1.Append 2.Search 3.Exit2
enter rollno to search9
Sorry, record not found
1.Append 2.Search 3.Exit3

BINARY FILE – CREATION AND UPDATION Date:19/08/21

14) Create a binary file with roll number, name and marks. Input a roll
number and search for it in the file, if found, update the marks to new
marks, otherwise , display an error message.
import pickle
def Append():
with open('stud.dat','ab')as file:
while True:
stud=[]
Rollno=int(input("Enter rollno"))
Name=input("Enter Name")
Marks=eval(input("Enter marks"))
stud=[Rollno,Name,Marks]
pickle.dump(stud,file)
ans=input("Continue(y/n)")
if ans=='n' or ans=='N':
break

def Update():
lst=[]
with open('stud.dat','rb+')as file:
found=False
file.seek(0)
r=int(input("enter rollno to update"))
while True:
try:
pos=file.tell()
stud=pickle.load(file)
if stud[0]==r:
print("Name : ",stud[1])
print("Marks: ",stud[2])
found=True
m=eval(input("Enter new marks"))
stud[2]=m
file.seek(pos)
pickle.dump(stud,file)
except EOFError:
break
if not found:
print("Record Not found")
while True:
opt=int(input("1.Append 2.Update 3.Exit"))
if opt==1:
Append()
elif opt==2:
Update()
elif opt==3:
break
else:
print("Invalid Code")

1.Append 2.Update 3.Exit1


Enter rollno1
Enter NameAarti
Enter marks80.5
Continue(y/n)y
Enter rollno2
Enter NameSheryl
Enter marks45.5
Continue(y/n)y
Enter rollno3
Enter NameKriti
Enter marks75
Continue(y/n)y
Enter rollno4
Enter NameSwati
Enter marks50
Continue(y/n)n
1.Append 2.Update 3.Exit2
enter rollno to update3
Name : Kriti
Marks: 75
Enter new marks85
1.Append 2.Update 3.Exit2
enter rollno to update3
Name : Kriti
Marks: 85
Enter new marks99
1.Append 2.Update 3.Exit3

CSV FILE Date:08/09/21


15) Create a CSV file (Emp.csv) for N employees where N is input by
the user with following details – Empid, Empname,Basic_Pay and
HRA(House Rent Allowance). Read the same file and calculate
Gross_Pay(Basic_Pay+HRA) for all employees and display the same.

import csv
fields=['Empid', 'Empname','Basic_Pay','HRA(House Rent Allowance)']
def Write():
with open('employee.csv','w',newline='') as f:
Writer=csv.writer(f)
Writer.writerow(fields)
n=int(input("Enter how many records"))
for i in range(n):
lst=eval(input("Enter Empid, Empname,Basic_Pay and
HRA(House Rent Allowance)"))
Writer.writerow(lst)

def Read():
with open('employee.csv','r') as f:
Reader=csv.reader(f)
cols=next(Reader)
print(' '.join(cols))
for i in Reader:
Grosspay=eval(i[2])+eval(i[3])
print(' '.join(i),Grosspay)

Write()
Read()
Output:

You might also like