Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as pdf or txt
Download as pdf or txt
You are on page 1of 57

1

1. WAP to input the student name and marks in 5 subjects.


Calculate total and percentage. Then find out the grade of the
student as per the given

CODE:

m1=int(input("Enter your marks in subject 1 out of 100: "))


m2=int(input("Enter your marks in subject 2 out of 100: "))
m3=int(input("Enter your marks in subject 3 out of 100: "))
m4=int(input("Enter your marks in subject 4 out of 100: "))
m5=int(input("Enter your marks in subject 5 out of 100: "))
p=(m1+m2+m3+m4+m5)/5
print("Your percentage is",p)
if p>=80:
g="A"
elif p>=60:
g="B"
elif p>=33:
g="C"
else:
g="F"
print("Your grade is",g)

Output:
Enter your marks in subject 1 out of 100: 98
Enter your marks in subject 2 out of 100: 96
Enter your marks in subject 3 out of 100: 95
Enter your marks in subject 4 out of 100: 95
Enter your marks in subject 5 out of 100: 100
Your percentage is 96.8
Your grade is A
2

2.WAP to input total units consumed by a customer, calculate and display total
bill amount to
be paid by the customer. It will be calculated as per the following criteria:
No. of units Rate (in Rs)
First 100 Units 1 Rs per unit.
Next 200 Units 2 Rs per unit.
Above 300 Units 4 Rs per unit
CODE:
u=int(input("Enter total units consumed: "))
x=u-100 y=x-200
if x<=0:
t=u*1
else:
if y<=0:
t=100+x*2
else:
t=100+400+y*4
print("Amount to be paid is",t)

Output:
Enter total units consumed: 500
Amount to be paid is 1300
3

3. Write a python program to check whether the entered character is an


alphabet or not.
CODE:
ch = input("Enter a character: ")
if ((ch>='a' and ch<= 'z') or (ch>='A' and ch<='Z')):
print(ch, "is an Alphabet")
else:
print(ch, "is not an Alphabet")

Output:
Enter a character: S
S is an Alphabet
4

4. Program to input n different numbers from user. Program will print the sum
of those numbers.
for example : if the n is 3, then ask any three numbers from user and suppose
user enters 1,3, 5 then the output should be : 9 (1+3+5)
CODE:
n=int(input("Enter how many numbers: "))
sum=0
for i in range(n):
a=int(input('Enter a number: '))
sum+=a
print('Sum of all numbes is',sum)

Output:
Enter how many numbers: 3
Enter a number: 1
Enter a number: 3
Enter a number: 5
Sum of all numbes is 9
5

5. Program to input age of n people. Program will count and print the
frequency of the people as per the given criteria.
CODE:

n=int(input('Enter a number='))
ch=0
ad=0
sr=0
for i in range(n):
age=int(input('Enter the age='))
if age<18:
ch+=1
elif age<60:
ad+=1
else:
sr+=1
print('Frequency of Children=',ch,end=””)
print('Frequency of Adult=',ad,end=””)
print('Frequency of Sr.Citizen=',sr,end=””)
Output:
Enter a number=5
Enter the age=18
Enter the age=32
Enter the age=67
Enter the age=16
Enter the age=72
Frequency of Children= 1 Frequency of Adult= 2 Frequency of Sr.Citizen= 2
6

6. Program to input ‘n’ numbers from user and print the largest number among
them.

CODE:
n=int(input('Enter the number of numbers: '))
l=0
for i in range(n):
a=int(input('Enter a number: '))
if l<a:
l=a
print('The largest number is',l)

Output:
Enter the number of numbers: 4
Enter a number: 21
Enter a number: 25
Enter a number: 29
Enter a number: 30
The largest number is 30
7

7. Program to input a string from user. The program will count and print the
frequency of
words present in the string.
CODE:
s=input("enter a string:")
count=0
for word in s.split():
print(word)
count+=1
print("total words:",count)

Output:
enter a string:Python is fun
Python
is
fun
total words: 3
8

8. Program to input n values in a tuple. Store odd and even numbers


individually in two
different tuples
CODE:
t=()
t1=()
t2=()
n=int(input('Enter number of elements of tuple: '))
for i in range(n):
x=int(input('Enter a number: '))
t=t+(x,)
if x%2==0:
t1+=(x,)
else:
t2+=(x,)
print(t) print(t1)
print(t2)
Output:
Enter number of elements of tuple: 5
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: 5
(1, 2, 3, 4, 5)
(2, 4)
(1, 3, 5)
9

9. Program to input n values in a list. Count and print the frequency of Positive,
Negative and
Zero values present in the list.
CODE:
:t=()
t1=0
t2=0
t3=0
n=int(input('Enter number of elements
of tuple: ')) for i in range(n):
x=int(input('Enter a number: '))
t=t+(x,) if x>0: t1+=1 elif x<0:
t2+=1 else: t3+=1 print(t)
print('Frequency of positive numbers is',t1)
print('Frequency of negative numbers is',t2)
print('Frequency of zeroes is',t3)
Output:
Enter number of elements of tuple: 5
Enter a number: -6
Enter a number: 0
Enter a number: 37
Enter a number: 56
Enter a number: -74
(-6, 0, 37, 56, -74)
Frequency of positive numbers is 2
Frequency of negative numbers is 2
Frequency of zeroes is 1
10

10. Program to input Rno, name, marks in five subjects(in list form) in a
dictionary. The program will calculate and add the percentage in the dictionary.
Print the entire dictionary on the screen.
CODE:
dict={} l=[]
t=0 dict['Rno']=int(input('Enter your
Rno: ')) dict['Name']=input('Enter your
name: ')
for i in range(5): x=int(input('Enter your
marks in a subject: '))
l.append(x)
t+=x 37
dict['Marks in subjects']=l
p=(t/500)*100
dict['percentage']=p print(dict)
Output:
Enter your Rno: 21
Enter your name: Shairia
Enter your marks in a subject: 98
Enter your marks in a subject: 96
Enter your marks in a subject: 95
Enter your marks in a subject: 95
Enter your marks in a subject: 100
{'Rno': 21, 'Name': 'Shairia', 'Marks in subjects': [98, 96, 95, 95, 100],
'percentage': 96.8}
1.WAUDF which accepts a list of numbers. Function prints all the odd and even
values present in the list individually.
CODE:
def odd_even (L):
print('Even values',end=':')
for i in L:
if i%2==0:
print(i,end=',')
print('\nOdd values',end=':')
for i in L:
if i%2!=0:
print(i,end=',')
L=[]
n=int(input('Enter number of elements of list: ')) for
i in range(n):
x=int(input('Enter a number: '))
L.append(x)
odd_even(L)

Output:
Enter number of elements of list: 4
Enter a number: 25
Enter a number: 26
Enter a number: 27
Enter a number: 28
Even values:26,28,
Odd values:25,27,
2.WAUDF which accepts a list of numbers. Function returns the frequency
of Positive, negative and zero values present in the list.
CODE:
def pnz(L):
p=0
n=0
z=0
for i in L:
if i>0:
p+=1

elif i<0:
n+=1

else:
z+=1
return p,n,z

L=[]
a=int(input('Enter number of elements of list: '))
for i in range(a):
x=int(input('Enter a number: '))
L.append(x)

p,n,z=pnz(L)
print('Frequency of Positive, Negative and zero values:',p,',',n,',',z)

Output:
Enter number of elements of list: 4
Enter a number: 0
Enter a number: -9
Enter a number: 12
Enter a number: -1
Frequency of Positive, Negative and zero values: 1 , 2 , 1
3.WAUDF which accepts a list of numbers. Function swaps the first half of
the list with its second half.
Code:
def swap(L):
l1=[]
l2=[]
c=len(L)
j=int(c/2)
if c%2==0:
l1=L[:c//2]
l2=L[j:]
L.clear()
L.extend(l2)
L.extend(l1)
return(L)
else:
l1=L[:(c//2)]
l2=L[c//2+1:]
l4=[L[c//2]]
L.clear()
L.extend(l2)
L.extend(l4)
L.extend(l1)
return(L)
L=[]
n=int(input('Enter number of elements of list: '))
for i in range(n):
x=int(input('Enter a number: '))
L.append(x)
print(L)

print(swap(L))
output:
Enter number of elements of list: 4
Enter a number: 55
Enter a number: 66
Enter a number: 77
Enter a number: 88
[55, 66, 77, 88]
[77, 88, 55, 66]
4.WAUDF which accepts two lists of integer type. Function will create a
new list which will have those values from both the lists which are
divisible by 7.
CODE:

def d7(l1,l2):

l=[]
print('List containing the values divisible by 7: ',end='')
for i in l1:
if i%7==0:
l.append(i)
for i in l2:
if i%7==0:
l.append(i)
return(l)

l1=[]
l2=[]
n=int(input('Enter number of elements of list: '))
for i in range(n):
x=int(input('Enter a number: '))
l1.append(x)
print(l1)
n=int(input('Enter number of elements of list: '))
for i in range(n):
x=int(input('Enter a number: '))
l2.append(x)
print(l2)
print(d7(l1,l2))
Output:

Enter number of elements of list: 4

Enter a number: 56

Enter a number: 98

Enter a number: 21

Enter a number: 0

[56, 98, 21, 0]

Enter number of elements of list: 4

Enter a number: 2

Enter a number: 7

Enter a number: 9

Enter a number: 1

[2, 7, 9, 1]

List containing the values divisible by 7: [56, 98, 21, 0, 7]


5. WAUDF which accepts a list of n numbers and a number. Function will
check if a number is present in the list or not. If the number is present,
return the position of the number otherwise return 0.

CODE:
def number_is_present_in_list(l,n):
if n in l:
return('Position of',n,'is:',l.index(n)+1)
else:
return(0)
l=[]
a=int(input('Enter number of elements of list: ')) for
i in range(a):
x=int(input('Enter a number: '))
l.append(x) print(l)
n=int(input('Enter a number to find it in the list: '))
print(number_is_present_in_list(l,n))
Output:
Enter number of elements of list: 4
Enter a number: 21
Enter a number: 0
Enter a number: 45
Enter a number: 68
[21, 0, 45, 68]
Enter a number to find it in the list: 0
('Position of', 0, 'is:', 2)
6. WAUDF which accepts a list of n numbers (Positive as well as negative).
Function creates two new lists, one having all positive numbers and the
other having all negative numbers from the given list. Print all three lists
inside the function.

CODE:

def pos_neg_list(l):
l1=[]
l2=[]
print('Original List:',l)
for i in l:
if i>0:
l1.append(i)
elif i<0:
l2.append(i)
print('List of positive values:',l1)
print('List of negative values:',l2)

l=[]
n=int(input('Enter number of elements of list: '))
for i in range(n):
x=int(input('Enter a number: '))
l.append(x)
pos_neg_list(l)
Output:
Enter number of elements of list: 4
Enter a number: 1
Enter a number: -2
Enter a number: 0
Enter a number: 4
Original List: [1, -2, 0, 4]
List of positive values: [1, 4]
List of negative values: [-2]
7. WAUDF EXTRA_ELE(A,B) in Python to find and display the extra element
in List A. List A contains all the elements of List B but one more element
extra. (Restriction: List elements are not in order).
Example If the elements of List A is 14, 21, 5, 19, 8, 4, 23, 11 and the
elements of List B is 23, 8, 19, 4, 14, 11, 5 Then output will be 21

CODE:
def EXTRA_ELE(A,B):
for i in A :
if i not in B:
return(i)

List_A=[14,21,5,19,8,4,23,11] List_B=[23,8,19,4,14,11,5]
print(EXTRA_ELE(List_A,List_B))

Output:
21
8.WAUDF arrange elements(X), that accepts a list X of integers and sets
all the negative elements to the left and all positive elements to the right
of the list.
Eg: if L =[1,-2,3,4,-5,7] , then the list should be: [-2,-5,1,3,4,7]

CODE:
def rearrange_list(l):

l1=[]
l2=[]
l3=[]
print('Original List:',l)
for i in l:
if i>0:
l1.append(i)
elif i<0:
l2.append(i)
else:
l3.append(i)
l.clear()
l.extend(l2)
l.extend(l3)
l.extend(l1)
return l

l=[]
n=int(input('Enter number of elements of list: '))
for i in range(n):
x=int(input('Enter a number: '))
l.append(x)
print('Rearranged list:',rearrange_list(l))
Output:
Enter number of elements of list: 4
Enter a number: 34
Enter a number: 43
Enter a number: 45
Enter a number: 54
Original List: [34, 43, 45, 54]
Rearranged list: [34, 43, 45, 54]
1. Write a function to count and display the number of spaces present
in a text file named “PARA.TXT”.

CODE:

def countspace():
file=open("PARA.txt",'r')
x=file.read()
c=0
for i in x:
if i==' ':
c+=1
print("frequency of spaces=",c)
file.close()
countspace()

PARA textfile:
Hi I live in India
It's capital is Delhi

Output:
frequency of spaces= 7

1
2. Write a function in PYTHON to count the number of lines ending with
a small vowel from a text file “STORY.TXT’.

CODE:

def vowels_lines():
file=open("STORY(1).txt",'r')
c=0
v=file.readline()
while v:
if len(v)>2:
if v[len(v)-2] in 'aeiou':
c+=1
v=file.readline()
print("frequency of lines ending with vowels is=",c)
file.close()
vowels_lines()

STORY(1) textfile:

I love pizza
My favourite place is Chicago

Output:
frequency of lines ending with vowels is= 2

2
3. . Write a function in PYTHON to count and display the number of
words starting with alphabet ‘A’ or ‘a’ present in a text file
“LINES.TXT”. Example: If the file “LINES.TXT” contains the following
lines, A boy is playing there. There is a playground. An aeroplane is
in the sky. Are you getting it? The function should display the output
as

CODE:
def start_a():
with open("Lines.txt",'r') as f1:
x=f1.read()
c=0
a=x.split()
for i in a:
if i[0] in'Aa':
c+=1
print("frequency of words startong from 'a' or 'A'=",c)
start_a()

LINES textfile:
A boy is playing there . There is a playground.
An aeroplane is in the sky.
Are you getting it?

Output:
frequency of words startong from 'a' or 'A'= 5

3
4. Write a function in PYTHON that counts the number of “Me” or
“My” words present in a text file “DIARY.TXT”. If the “DIARY.TXT”
contents are as follows: My first book was Me and My Family. It gave
me chance to be Known to the world. The output of the function
should be: Count of Me/My in file: 4

CODE:
def countmemy():
with open("Diary.txt") as file:
x=file.read()
c=0
a=x.split()
for i in a:
if i in "'ME' 'MY' 'My''Me' 'me' 'my'":
c+=1
print("The frequency of 'me' and 'my'=",c)
countmemy()

DIARY textfile:

Me and my family enjoy a lot together.


I wrote a book me and my family
Me and my family is bestseller

Output:
The frequency of 'me' and 'my'= 6

4
5. Write a function in PYTHON to read the contents of a text file
“Places.Txt” and display all
those lines on screen which are either starting with ‘P’ or with ‘S’

CODE:

def P_S():
with open ("Places.txt") as f:
a=f.read()
c=0
w=a.splitlines()
for i in w:
if i[0] in 'PS':
c+=1
print(i)
print("The number of sentences starting from P and S are=",c)
P_S()

PLACES textfile:
Parrot is a green color bird
Sparrow is mostly brown colored
Crow is black color bird
Peacock is my favourite one!!

Output:
Parrot is a green color bird
Sparrow is mostly brown colored
Peacock is my favourite one!!
The number of sentences starting from P and S are= 3

5
5. Write a function copy() that will copy all the words starting with an
uppercase alphabet from an existing file “FAIPS.TXT” to a new file
“DPS.TXT”

CODE:
def copy():
with open("Faips.txt")as file:
with open("DPS.txt",'w') as f:
x=file.read()
a=x.split()
for i in a:
if i[0]>='A' and i[0]<='Z':
f.write(i+"\n")
copy()

Faips textfile:
India is diverse country
Delhi is capital of India
Indian food is famous

DPS textfile:
India
Delhi
India
Indian

6
7. Write a function show(n) that will display the nth character from
the existing file “MIRA.TXT”. If the total characters present are less
than n, then it should display “invalid n”.

CODE:
def show(n):
f=open("MIRA.txt",'r')
r=f.read()
if n<=len(r):
print("The character at",n,"is=",r[n-1])
else:
print("Invalid n")
f.close()
n=int(input("enter a number="))
show(n)

MIRA textfile:
Mira is a smart girl
she is very intelligent
she is from Delhi
but currently she lives in Chicago

output:
enter a number=13
The character at 13 is= a

7
8. Assuming that a text file named TEXT1.TXT already contains
some text written into it, write a function named vowelwords(), that
reads the file TEXT1.TXT and creates a new file named
TEXT2.TXT, which shall contain only those words from the file
TEXT1.TXT which don’t start with an uppercase vowel (i.e., with ‘A’,
‘E’, ‘I’, ‘O’, ‘U’).
For example,
if the file TEXT1.TXT contains Carry Umbrella and Overcoat When
It rains Then the text file TEXT2.TXT shall contain Carry and When
rains

CODE:
def vowelwords():
with open("TEXT1.txt") as file1:
with open("TEXT2.txt",'w') as file2:
f=file1.read()
a=f.split()
for i in a :
if i[0] not in 'AEIOU':
file2.write(i+' ')
vowelwords()

Text1 textfile:
Carry Umbrella and Overcoat When it rains

Text2 textfile:

Carry and When it rains

8
9. Write a function in PYTHON to display the last 3 characters of a
text file “STORY.TXT

CODE:
def lastthree():
with open("STORY.txt") as f1:
x=f1.read()
a=len(x)
print("last three characters+")
for i in x:
lst.append(i)
for j in lst[a-3:a]:
print(j,end='@')
lastthree()

Story textfile:
Be yourself
You are amazing

Output:
last three characters+
i@n@g@

9
10.Write a function EUCount() in PYTHON, which should read each
character of a text file IMP.TXT, should count and display the
occurrences of alphabets E and U (including small cases e and u
too). Example: If the file content is as follows: Updated information Is
simplified by official websites. The EUCount() function should
display the output as: E:4 U:1
CODE:
def EUCount():
with open("IMP.txt") as f1:
x=f1.read()
counte=0
countu=0
for i in x:
if i in 'Ee':
counte+=1
elif i in'Uu':
countu+=1
print("E:",counte,"\nU:",countu)
EUCount()

IMP textfile:
Updated information
Is simplified by official websites

Output:
E: 4
U: 1

10
11. Write function definition for SUCCESS( ) in PYTHON to read the
content of a text file STORY.TXT, count the presence of word
SUCCESS and display the number of occurrence of this word. Note
: – The word SUCCESS should be an independent word – Ignore
type cases (i.e. lower/upper case) Example : If the content of the file
STORY.TXT is as follows : Success shows others that we can do it.
It is possible to achieve success with hard work. Lot of money does
not mean SUCCESS. The function SUCCESS( ) should display the
following : 3
CODE:
def SUCESS():
with open("STRORY(2).txt") as f1:
r=f1.read()
s=r.split()
c=0
for i in s:
if i in "'SUCCESS' 'Success' 'success'":
c+=1
print("Frequency of SUCCESS is=",c)
SUCCESS()

Story(2) textfile:
Success shows others that we can do it.
Hardwork can help us achieve Success
Output:
Frequency of SUCCESS is= 2
12. Write the function definition for WORD4CHAR() in PYTHON to read
the content of a text file FUN.TXT, and display all those words, which
have four characters in it. Example: If the content of the file Fun.TXT is as
11
follows: When I was a small child, I used to play in the garden with my
grand mom. Those days were amazingly funful and I remember all the
moments of that time The function WORD4CHAR() should display the
following: When used play with days were that time
CODE:
def WORD4CHAR():
with open("FUN.txt") as file1:
x=file1.read()
a=x.split()
lst=[]
for i in a:
s=len(i)
if s==4:
lst.append(i)
for i in lst:
print(str(i),end=' ')
WORD4CHAR()
FUN textfile:
When I was a small child, I used to play in the garden with my grand
mom. Those days were
amazingly funful and I remember all the moments of that time
output:
When used play with mom. days were that time
13. Write function definition for DISP3CHAR() in PYTHON to read the
content of a text file KIDINME.TXT, and display all the Palindrome Words
present in it.
CODE:
def DISP3CHAR():
12
with open("KIDINME.txt") as file1:
x=file1.read()
a=x.split()
print("Palindrome strings is=",end=' ')
for i in a:
str=i[::-1]
if i==str:
print(i,end=', ')
DISP3CHAR()
Kidinme textfile:
I feel bored at home during pandemic situation
I love to go out with my friends
But now that i can't go out more often
it is very boring
output:
Palindrome strings is= I, I, i,

13
14. . Write a function in Python to copy the contents of a text file into
another text file. The names of the files should be input from the
user.

CODE:
def copy():
cf=input("enter the name of the file from where you want to copy
the text from=")
ct=input("Enter the name of the file=")
f=cf+".txt"
e=ct+" .txt"
with open(f) as f1:
with open(e,'w') as f2:
x=f1.read()
a=f2.write(x)
copy()

Copy text material from textfile:


COPY THIS FILE!!!!

Copied textfile:
COPY THIS FILE!!!!

14
15. Write a function in Python which accepts two text file names as
parameters. The function
should copy the contents of first file into the second file in such a
way that all multiple consecutive
spaces are replaced by a single space.
For example, if the first file contains:
Self conquest is the greatest victory .
then after the function execution, second file should contain:
Self conquest is the greatest victory .

CODE:
def copywsp(cf,ct):
with open(cf) as f1:
with open (ct,'w') as f2:
x=f1.read()
for i in x:
while ' ' in x:
x=x.replace(' ',' ')
f2.write(x)
copywsp("DRAMA.txt"."DRAMA2")

DRAMA textfile:
I love watching korean dramas
They are the best stress buster.

DARAMA2 textfile:
I love watching korean dramas
They are the best stress buster.

15
16. Write a function in Python to input a multi-line string from the
user and write this string into a file named ‘Story.txt’. Assume that
the file has to be created.
CODE:
def writinglines():
with open("Story(3).txt",'w') as f1:
print("Press '0' to exist or enter to add the lines")
while True:
lines=input("enter a string=")
if lines=='0':
break
else:
f1.write(lines+'\n')
writinglines()

output:
Press '0' to exist or enter to add the lines
enter a string=Smile always
enter a string=it makes you look beautiful
enter a string=0

Story(3) textfile:
Smile always
it makes you look beautiful

16
17. Write a function to display the last line of a text file. The name of
the text file is passed as an
argument to the function
CODE:
def lastline(f):
with open(f) as f1:
x=f1.read()
a=x.splitlines()
print("last line=",a[len(a)-1])
lastline("Story(3).txt")

Story(3):
Smile always
it makes you look beautiful

output:
last line= it makes you look beautiful

17
18. Write a Python function to read and display a text file
'BOOKS.TXT'. At the end, program displays number of lowercase
characters, uppercase characters and digits present in the text file.

CODE:
def culd():
with open("BOOKS.txt") as f1:
x=f1.read()
cu,cl,cd=0,0,0
for i in x:
if i>='a' and i<='z':
cl+=1
elif i>='A' and i<='Z':
cu+=1
elif i>='0' and i<='9':
cd+=1
print("frequency of lowercas alphabet",cl,"\nfrequency of
uppercase alphabets=",cu,"\nfrequency of digits=",cd)
culd()

Books textfile:
Book number 001=The fault in our stars
Book number 002=The Alchemist
Book number 003=The monk who sold his Ferrari

Outfit:
frequency of lowercas alphabet 77
frequency of uppercase alphabets= 7
frequency of digits= 9

18
19. Write a Python function to display the size of a text file after
removing all the white spaces (blanks, tabs, and EOL characters).

CODE:
def countwwsteol():
with open ("Space.txt") as file1:
x=file1.read()
c=len(x)
f=0
for i in x:
while ' ' in x:
x=x.replace(' ','')
if i in "' ''\t''\n'":
f=f+1
print("length of the file after removing all white spaces,tabs
and Eol character",c-f)
countwwsteol()

space textfile:
This file is for checking length

Output:
length of the file after removing all white spaces,tabs and Eol
character 27

19
20.Write a function display( ) which reads a file story.txt and display
all those words in reverse order which are started with ‘I’ letter.
Example: Suppose the file contains: India is great country. The
function should display : aidnI si great country

CODE:

def display():
with open("file story.txt") as f1:
x=f1.read()
a=x.split()
for i in a:
if i[0] in 'Ii':
i=i[::-1]
print(i,end=' ')
display()

file story textfile:


India is great country.
The function should display :
aidnI si great country

output:
India is great country.
The function should display :
aidnI si great country

20
1. Consider a binary file “STUDENT.DAT” which contains records of
the following
type:
[S_Admno, S_Name, Percentage]
Description of these three values are:
S_Admno – Admission Number of student (string)
S_Name – Name of student (string)
Percentage – Marks percentage of student (float)

CODE:
import pickle as pk
def create():
with open("Student.dat",'ab') as ifile:
print("enter '0' to exit and '1' to add a record")
while True:
ch=int(input("enter '0' or '1'="))
if ch==0:
break
elif ch==1:
lst=[]
s_ando=input("enter student's admission number:")
s_name=input("enter the name of the student=")
per=float(input("enter the percentage of the student="))
lst.extend([s_ando,s_name,per])
pk.dump(lst,ifile)
def more_than_75():
with open("Student.dat",'rb') as ofile:
try:
while True:
var=pk.load(ofile)
if var[2]>=75.0:
print(var)
except EOFError:
pass
create()
more_than_75()
output:
enter '0' to exit and '1' to add a record
enter '0' or '1'=1
enter student's admission number:4754
enter the name of the student=Sara
enter the percentage of the student=95
enter '0' or '1'=1
enter student's admission number:4755
enter the name of the student=Rohan
enter the percentage of the student=92
enter '0' or '1'=0
['4754', 'Sara', 95.0]
['4755', 'Rohan', 92.0]
2. Write a function in PYTHON to search for a BookNo from a binary file
“BOOK.DAT”, assuming the binary file is containing the records of the following
type:
(BookNo,Bname,Price)
code:
import os
import pickle
def create():
ifile = open('bookno.dat','ab')
bno =int(input('enter the book number:- '))
name = (input('enter the name of the book:- '))
price = int(input('enter the price:- '))
data = (bno,name,price)
pickle.dump(data,ifile)
ifile.close()
def search():
a= int(input('enter the bookno. of the book you want to search :- '))
try :
with open("bookno.dat","rb") as afile :
while True:
data = pickle.load(afile)
if data[0]== a :
print('the record is :- ',data)

except EOFError:
pass

def display():
try :
with open("bookno.dat","rb") as afile :
while True:
data = pickle.load(afile)
print(data)

except EOFError:
pass

while True:
print("1. add record \n 2. display \n 3. search \n 4. exit")
ch= int(input(" enter your choice:-"))
if ch==1:
create()
elif ch==2:
display()
elif ch==3:
search()
else:
break

create()
search()
display()
output:
1. add record
2. display
3. search
4. exit
enter your choice:-1
enter the book number:- 888
enter the name of the book:- the fault in our stars
enter the price:- 500
1. add record
2. display
3. search
4. exit
enter your choice:-1
enter the book number:- 788
enter the name of the book:- stargirl
enter the price:- 400
1. add record
2. display
3. search
4. exit
enter your choice:-4
enter the book number:- 888
enter the name of the book:- the fault in our stars
enter the price:- 500
enter the bookno. of the book you want to search :- 888
the record is :- (888, 'the fault in our stars', 500)
the record is :- (888, 'the fault in our stars', 500)
(888, 'the fault in our stars', 500)
(788, 'stargirl', 400)
(888, 'the fault in our stars', 500)
>>>
3. Assuming that a binary file VINTAGE.DAT contains records of the following type,
write a function in PYTHON to read the data VINTAGE.DAT and display those
vintage vehicles, which are priced between 200000 and 250000.
[VNO, VDesc, price]

Code:

import pickle

se = 1
ifile = open('cars.DAT','ab')
while True :
print('car number :- ',se)
VNO = int(input('enter the VNO:- '))
VDesc = str(input('enter the VDesc:- '))
price = int(input('enter the price:- '))
data = [VNO,VDesc,price]
pickle.dump(data,ifile)
a = input('do you want to input another record? (n/y)')
se +=1
if a == 'n' :
break
ifile.close()

readrec=1
try:
with open("cars.dat","rb") as bfile :
a = []
print('cars which are priced between 200000 and 250000 are :- ',)
while True:
edata=pickle.load(bfile)
if edata[2] >= 200000 and edata[2] <= 250000 :
a.append(edata)

except EOFError:
pass
bfile.close()

for i in a:
print(i)
output:
car number :- 1
enter the VNO:- 666
enter the VDesc:- mercedes
enter the price:- 210000
do you want to input another record? (n/y)y
car number :- 2
enter the VNO:- 888
enter the VDesc:- bmw
enter the price:- 190000
do you want to input another record? (n/y)y
car number :- 3
enter the VNO:- 777
enter the VDesc:- r.r
enter the price:- 220000
do you want to input another record? (n/y)n
cars which are priced between 200000 and 250000 are :-
[123, 'dsgds', 230000]
[89786, 'hgfsdfgvjgj', 210000]
[666, 'mercedes', 210000]
[777, 'r.r', 220000]
>>>
4. Write a function in PYTHON to read each record of a binary file
ITEMS.DAT, find
and display those items which costs less than 2500. Assume that the
file
ITEMS.DAT is created with the help of objects of the following type:
{"ID":string, "GIFT":string, "Cost":integer};
CODE:
import pickle as pk
def create():
with open("items.dat",'wb') as ifile:
print("enter '0' to exit or '1' to enter the details of item")
while True:
ch=int(input("enter a choice:"))
if ch==0:
break
elif ch==1:
d1={}
idof=input("enter the id of the item=")
d1["ID"]=idof
gift=input("enter the name of the item=")
d1["GIFT"]=gift
price=int(input("enter the price of the item"))
d1["COST"]=price
pk.dump(d1,ifile)
def itemsforgift():
with open("items.dat",'rb') as ofile:
try:
while True:
ite=pk.load(ofile)
if ite['COST']<=2500:
print(ite)
except EOFError:
pass
create()
itemsforgift()
output:
enter '0' to exit or '1' to enter the details of item
enter a choice:1
enter the id of the item=A01
enter the name of the item=Sling bag
enter the price of the item500
enter a choice:1
enter the id of the item=A02
enter the name of the item=Perfume
enter the price of the item400
enter a choice:0
{'ID': 'A01', 'GIFT': 'Sling bag', 'COST': 500}
{'ID': 'A02', 'GIFT': 'Perfume', 'COST': 400}
5. Write a definition for function BUMPER() in PYTHON to read each
object of a
binary file GIFTS.DAT. The function will search and change the
remarks of those
gifts which have remarks as “ON DISCOUNT” and their price is more
than 1000.
New Remarks should be “NOT ON DISCOUNT”.
Assume that the file GIFTS.DAT belongs to following type:
(ID, Gift, Remarks, Price)
Code:
import pickle as pk
def create():
with open("gifts.dat",'wb') as ifile:
print("enter '0' to exit and '1' to enter a book detail")
while True:
ch=int(input("enter choice="))
if ch==0:
break
elif ch==1:
t=()
idof=int(input("enter the id of the item="))
gift=input("enter the name of the item=")
remark=input("enter the remark for the item=")
price=int(input("enter the price of the item="))
t=t+(idof,gift,remark,price,)
pk.dump(t,ifile)
def searchandchange():
flag=True
with open("gifts.dat",'rb') as ofile:
try:
while True:
l=pk.load(ofile)
y=list(l)
if y[2].upper()=='ON DISCOUNT' and y[3]>=1000:
y[2]="NOT ON DISCOUNT"
print(tuple(y))
flag=False
except EOFError:
if flag==True:
print("Data not found")
pass
create()
searchandchange()
output:

enter '0' to exit and '1' to enter a book detail


enter choice=1
enter the id of the item=678
enter the name of the item=hellooo
enter the remark for the item=on discount
enter the price of the item=800
enter choice=1
enter the id of the item=666
enter the name of the item=eeee
enter the remark for the item=on discount
enter the price of the item=1500
enter choice=0
(666, 'eeee', 'NOT ON DISCOUNT', 1500)
>>>
6. Consider a binary file “PRODUCT.DAT” which contains the data of dictionary
type. The structure of dictionary is given below:
{"prod_code":value, "prod_desc":value, "stock":value}
prod_code and prod_desc belong to strings and stock is an integer.
Write a function in PYTHON to update the file with a new value of stock. New
value of stock and product_code(whose stock is to be updated) are to be inputted
during the execution of the function

code:
import pickle as pk
import os
def create():
STU={}
with open("PRODUCTS.DAT",'wb') as ifile:
print("Enter '0' to exit and '1' to enter a product's details:")
while True:
ch=int(input("Enter choices: "))
if ch==0:
break
elif ch==1:
STU['prod_code']=input("Enter code: ")
STU['prod_desc']=input("Enter products's name: ")
STU['stock']=int(input("Enter stock ofproduct:"))
pk.dump(STU,ifile)
def update():
flag=True
ifile=open("PRODUCTS.DAT",'rb+')
n=input('Enter the product code of the product with changed stock: ')
try:
while True:
pos=ifile.tell()
l=pk.load(ifile)
if l['prod_code']==n:
print(l)
l['stock']=int(input('Enter new stock value:'))
print('Data updated')
ifile.seek(pos)
pk.dump(l,ifile)
flag=False
except EOFError:
if flag==True:
print("Data Not Found")
else:
ifile.close()
pass
def display():
ifile=open("PRODUCTS.DAT",'rb')
try:
while True:
print(pk.load(ifile))
except EOFError:
ifile.close()
pass
create()
update()
display()
output:
Enter '0' to exit and '1' to enter a product's details:
Enter choices: 1
Enter code: 677
Enter products's name: apple
Enter stock ofproduct:5
Enter choices: 1
Enter code: 776
Enter products's name: cherry
Enter stock ofproduct:6
Enter choices: 0
Enter the product code of the product with changed stock: 776
{'prod_code': '776', 'prod_desc': 'cherry', 'stock': 6}
Enter new stock value:8
Data updated
{'prod_code': '677', 'prod_desc': 'apple', 'stock': 5}
{'prod_code': '776', 'prod_desc': 'cherry', 'stock': 8}
>>>

You might also like