Python Updated
Python Updated
█ - Input by User
█ - Desired Output
█ - Computer Generated Message
# Q.1:
# Write a Python Program to enter a string and count the:
# (i) Number of alphabets.
# (ii) Number of digits.
# (iii) Spaces.
# (iv) Special Characters.
INPUT:
cust = input("Enter a string: ")
cust.lower()
tot = len(cust)
custcount = cust.count("a") + cust.count("b") + cust.count("c") + cust.count("d") +
cust.count("e") + cust.count("f") + cust.count("g") + cust.count("h") + cust.count("i") +
cust.count("j") + cust.count("k") + cust.count("l") + cust.count("m") + cust.count("n") +
cust.count("o") + cust.count("p") + cust.count("q") + cust.count("r") + cust.count("s") +
cust.count("t") + cust.count("u") + cust.count("v") + cust.count("w") + cust.count("x") +
cust.count("y") + cust.count("z")
spaces = cust.count(" ")
no = cust.count("0") + cust.count("1") + cust.count("2") + cust.count("3") + cust.count("4") +
cust.count("5") + cust.count("6") + cust.count("7") + cust.count("8") + cust.count("9")
spec = tot - custcount - no - spaces
print("(i) The number of alphabets in the string inputted by you is: ", custcount)
print("(ii) The number of digits in the string inputted by you is: ", no)
print("(iii)The number of spaces in the string inputted by you is: ", spaces)
print("(iv) The number of special characters in the string inputted by you is: ", spec)
OUTPUT:
Enter a string: CoMpUtEr_@_ScIeNcE_@_123
(i) The number of alphabets in the string inputted by you is: 7
(ii) The number of digits in the string inputted by you is: 3
(iii) The number of spaces in the string inputted by you is: 0
(iv) The number of special characters in the string inputted by you is: 14
# Q.2 (a):
# Write a Python Program to enter a string and display it in the following format:
# Input string: COMPUTER
# Output string: C
# CO
# COM
# COMP
# COMPU
# COMPUT
# COMPUTE
# COMPUTER
INPUT:
cust = input("Enter a string: ")
for i in range(len(cust)):
print("The output string is: \n")
print(cust[: i + 1])
OUTPUT:
Enter a string: COMPUTERSCIENCE
The output string is:
C
The output string is:
CO
The output string is:
COM
The output string is:
COMP
The output string is:
COMPU
The output string is:
COMPUT
The output string is:
COMPUTE
The output string is:
COMPUTER
The output string is:
COMPUTERS
The output string is:
COMPUTERSC
The output string is:
COMPUTERSCI
The output string is:
COMPUTERSCIE
The output string is:
COMPUTERSCIEN
The output string is:
COMPUTERSCIENC
The output string is:
COMPUTERSCIENCE
# Q.2 (b):
# Write a Python Program to enter a string and display it in the following format:
# Input string: COMPUTER
# Output string: C
# O
# M
# P
# U
# T
# E
# R
INPUT:
cust = input("Enter a string: ")
for i in range(len(cust)):
print("The output string is: \n")
print(cust[i], end='\n')
OUTPUT:
Enter a string: COMPUTERSCIENCE
The output string is:
C
The output string is:
O
The output string is:
M
The output string is:
P
The output string is:
U
The output string is:
T
The output string is:
E
The output string is:
R
The output string is:
S
The output string is:
C
The output string is:
I
The output string is:
E
The output string is:
N
The output string is:
C
The output string is:
E
# Q.3:
# Write a Python Program to enter a string and reverse the case of each character. Also, replace
every non-alphabet
# with '@'.
# Example:
# Input String: I like Computer Science 123
# Output String: i@LIKE@cOMPUTER@sCIENCE@@@@
INPUT:
cust = input("Enter a string: ")
st1 = ''
for i in range(len(cust)):
if cust[i].isupper():
st1 += cust[i].lower()
elif cust[i].islower():
st1 += cust[i].upper()
else:
st1 += '@'
print("The string inputted by you was: ")
print(cust, '\n')
print("The string after reversing the case of each alphabet and replacing every non-alphabetical
character with a '@' is: ")
print(st1)
OUTPUT:
Enter a string: I am Revanta Choudhary of Class 12-C.
The string inputted by you was:
I am Revanta Choudhary of Class 12-C.
The string after reversing the case of each alphabet and replacing every non-alphabetical
character with a '@' is:
i@AM@rEVANTA@cHOUDHARY@OF@cLASS@@@@c@
# Q.4:
# Write a Python Program:
# (i) To create a list of size 'n'.
# (ii) Add an element.
# (iii) Add multiple elements.
# (iv) Display the list.
# (v) Display the list in reverse.
# (vi) Enter an index position and display the list value at that position.
INPUT:
def main():
l1 = []
c = 'y'
while c == 'y' or c == 'Y' or c == 'Yes' or c == 'yes':
print("Enter '1' to create a list.")
print("Enter '2' to add an element.")
print("Enter '3' to add multiple elements.")
print("Enter '4' to display the list.")
print("Enter '5' to display the list in reverse.")
print("Enter '6' to display a specific element from the list.")
ch = int(input("Enter your choice: "))
if ch == 1:
create(l1)
elif ch == 2:
add_one(l1)
elif ch == 3:
add_multiple(l1)
elif ch == 4:
lis_disp(l1)
elif ch == 5:
lis_rev(l1)
elif ch == 6:
lis_val(l1)
else:
print("Please enter a valid input.")
c = input("Do you want to continue? \n")
def create(l1):
n = int(input("To create a list, first enter the number of elements you want in it: "))
for i in range(n):
val = input("Enter a value to add to your new list: ")
l1.append(val)
def add_one(l1):
val1 = input("Enter a value to add to your existing list: ")
l1.append(val1)
def add_multiple(l1):
l_temp = []
s = int(input("Enter the number of values you want to add to your existing list: "))
for i in range(s):
val2 = input("Enter a value to add to your existing list: ")
l_temp.append(val2)
l1.extend(l_temp)
def lis_rev(l1):
rev = l1[::-1]
print("The list in reverse is: ", rev)
def lis_disp(l1):
print("The list is: ", l1)
def lis_val(l1):
print("There are ", len(l1), " values in the list.")
b = int(input("Choose which index value from the list you want to see specifically, starting
from '0': "))
for t in range(len(l1)):
if t == b:
print(l1[t])
main()
OUTPUT:
Enter '1' to create a list.
Enter '2' to add an element.
Enter '3' to add multiple elements.
Enter '4' to display the list.
Enter '5' to display the list in reverse.
Enter '6' to display a specific element from the list.
Enter your choice: 1
To create a list, first enter the number of elements you want in it: 5
Enter a value to add to your new list: Revanta
Enter a value to add to your new list: Amogh
Enter a value to add to your new list: Disha
Enter a value to add to your new list: Annanya
Enter a value to add to your new list: Shreya
Do you want to continue?
y
Enter '1' to create a list.
Enter '2' to add an element.
Enter '3' to add multiple elements.
Enter '4' to display the list.
Enter '5' to display the list in reverse.
Enter '6' to display a specific element from the list.
Enter your choice: 2
Enter a value to add to your existing list: Smrit
Do you want to continue?
y
Enter '1' to create a list.
Enter '2' to add an element.
Enter '3' to add multiple elements.
Enter '4' to display the list.
Enter '5' to display the list in reverse.
Enter '6' to display a specific element from the list.
Enter your choice: 3
Enter the number of values you want to add to your existing list: 2
Enter a value to add to your existing list: Daksh
Enter a value to add to your existing list: Simran
Do you want to continue?
y
Enter '1' to create a list.
Enter '2' to add an element.
Enter '3' to add multiple elements.
Enter '4' to display the list.
Enter '5' to display the list in reverse.
Enter '6' to display a specific element from the list.
Enter your choice: 4
The list is: ['Revanta', 'Amogh', 'Disha', 'Annanya', 'Shreya', 'Smrit', 'Daksh', 'Simran']
Do you want to continue?
y
Enter '1' to create a list.
Enter '2' to add an element.
Enter '3' to add multiple elements.
Enter '4' to display the list.
Enter '5' to display the list in reverse.
Enter '6' to display a specific element from the list.
Enter your choice: 5
The list in reverse is: ['Simran', 'Daksh', 'Smrit', 'Shreya', 'Annanya', 'Disha', 'Amogh', 'Revanta']
Do you want to continue?
y
Enter '1' to create a list.
Enter '2' to add an element.
Enter '3' to add multiple elements.
Enter '4' to display the list.
Enter '5' to display the list in reverse.
Enter '6' to display a specific element from the list.
Enter your choice: 6
There are 9 values in the list.
Choose which index value from the list you want to see specifically, starting from '0': 0
Revanta
Do you want to continue?
n
# Q.5:
# Write a Python Program to perform the following functions/ operations:
# (i) Enter a user input for a list of size 'n'.
# (ii) Enter the start and end position and then display the list values in between them.
# (iii) Display the number of values in the list.
# (iv) Enter specific position in the list where you want to add a new value.
# (v) Insert a value at the end of the list.
# (vi) Insert multiple values at the end of the list.
# (vii) Remove an item from/ at a user inputted index position.
# (viii) Remove the last item of the list.
# (ix) Remove a particular inputted value from the list.
# (x) Clear/ Empty the list.
# (xi) Display the list in reverse.
# (xii) Display the sorted list in ascending order (ascending as default).
# (xiii) Display the sorted list in descending order.
# (xiv) Display the list.
INPUT:
def main():
l = []
c = 'y'
while c == 'y' or c == 'Y' or c == 'Yes' or c == 'yes' or c == 'YES':
print("Enter '1' to create a list.")
print("Enter '2' to display a specific range of the list.")
print("Enter '3' to display the total number of values in the list.")
print("Enter '4' to input a new value at a specified position in the list.")
print("Enter '5' to input a new value at the end of the list.")
print("Enter '6' to input multiple new values at the end of the list.")
print("Enter '7' to remove a specified value from the list by specifying its position in the
list.")
print("Enter '8' to remove the last value from the list.")
print("Enter '9' to remove a specified value from the list.")
print("Enter '10' to clear/ empty the list.")
print("Enter '11' to display the list in reverse.")
print("Enter '12' to display the list in a sorted manner, i.e. alphabetically ascending order
(by default).")
print("Enter '13' to display the list in alphabetically descending order.")
print("Enter '14' to display the list.")
ch = int(input("Enter your choice: "))
if ch == 1:
create(l)
elif ch == 2:
spec_list(l)
elif ch == 3:
tot_v(l)
elif ch == 4:
spec_val(l)
elif ch == 5:
addval_end(l)
elif ch == 6:
multival_end(l)
elif ch == 7:
specpos_valrem(l)
elif ch == 8:
remval_end(l)
elif ch == 9:
spec_valrem(l)
elif ch == 10:
lis_rem(l)
elif ch == 11:
lis_rev(l)
elif ch == 12:
lis_asc(l)
elif ch == 13:
lis_desc(l)
elif ch == 14:
lis_disp(l)
else:
print("Please enter a valid input.")
c = input("Do you want to continue? \n")
def create(l):
n = int(input("To create a list, first enter the number of elements you want in it: "))
for i in range(n):
val = input("Enter a value to add to your list: ")
l.append(val)
print("The current list is: ", l)
def spec_list(l):
n1 = int(input("Enter from which index position you want the sub list to start from: "))
n2 = int(input("Enter by which index position you want the sub list to end: "))
print("The sub list is: ", l[n1: n2 + 1])
def tot_v(l):
print("The number of values in the list are: ", len(l))
def spec_val(l):
n4 = int(input("Enter the position in the list where you want to add a new value: "))
str = input("Input the value you wish to add in the list: ")
l.insert(n4, str)
print("The list is now: ", l)
def addval_end(l):
s = input("Type a value you want to add to the end of the list: ")
l.append(s)
print("The list is now: ", l)
def multival_end(l):
s1 = int(input("Type the number of values you want to add to the end of the list: "))
for i3 in range(s1):
s2 = input("Type a value you want to add to the end of the list: ")
l.append(s2)
print("The list after adding the value(s) you specified to the end of the list is: ", l)
def specpos_valrem(l):
k = int(input("Type the index position of the value you wish to remove from the list: "))
for i1 in range(len(l)):
if i1 == k:
l.remove(l[i1])
print("The list after removing a value from the specified index position is: ", l)
else:
pass
def remval_end(l):
l.remove(l[-1])
print("The list after removing its last value is: ", l)
def spec_valrem(l):
b = input("Type the exact value you want to remove from the list: ")
for i2 in l:
if i2 == b:
l.remove(i2)
print("The list after removing the specified value is: ", l)
else:
pass
def lis_rem(l):
l.clear()
print("The removed list is: ", l)
def lis_rev(l):
rev = l[::-1]
print("The list in reverse is: ", rev)
def lis_asc(l):
l.sort()
print("The sorted list, i.e. in alphabetically ascending order is: ", l)
def lis_desc(l):
l.sort(reverse=True)
print("The sorted list, i.e. in alphabetically descending order is: ", l)
def lis_disp(l):
print("The current list is: ", l)
main()
OUTPUT:
Enter '1' to create a list.
Enter '2' to display a specific range of the list.
Enter '3' to display the total number of values in the list.
Enter '4' to input a new value at a specified position in the list.
Enter '5' to input a new value at the end of the list.
Enter '6' to input multiple new values at the end of the list.
Enter '7' to remove a specified value from the list by specifying its position in the list.
Enter '8' to remove the last value from the list.
Enter '9' to remove a specified value from the list.
Enter '10' to clear/ empty the list.
Enter '11' to display the list in reverse.
Enter '12' to display the list in a sorted manner, i.e. alphabetically ascending order (by default).
Enter '13' to display the list in alphabetically descending order.
Enter '14' to display the list.
Enter your choice: 1
To create a list, first enter the number of elements you want in it: 5
Enter a value to add to your list: Revanta
The current list is: ['Revanta']
Enter a value to add to your list: Disha
The current list is: ['Revanta', 'Disha']
Enter a value to add to your list: Amogh
The current list is: ['Revanta', 'Disha', 'Amogh']
Enter a value to add to your list: Annanya
The current list is: ['Revanta', 'Disha', 'Amogh', 'Annanya']
Enter a value to add to your list: Shreya
The current list is: ['Revanta', 'Disha', 'Amogh', 'Annanya', 'Shreya']
Do you want to continue?
y
Enter '1' to create a list.
Enter '2' to display a specific range of the list.
Enter '3' to display the total number of values in the list.
Enter '4' to input a new value at a specified position in the list.
Enter '5' to input a new value at the end of the list.
Enter '6' to input multiple new values at the end of the list.
Enter '7' to remove a specified value from the list by specifying its position in the list.
Enter '8' to remove the last value from the list.
Enter '9' to remove a specified value from the list.
Enter '10' to clear/ empty the list.
Enter '11' to display the list in reverse.
Enter '12' to display the list in a sorted manner, i.e. alphabetically ascending order (by default).
Enter '13' to display the list in alphabetically descending order.
Enter '14' to display the list.
Enter your choice: 2
Enter from which index position you want the sub list to start from: 0
Enter by which index position you want the sub list to end: 1
The sub list is: ['Revanta', 'Disha']
Do you want to continue?
y
Enter '1' to create a list.
Enter '2' to display a specific range of the list.
Enter '3' to display the total number of values in the list.
Enter '4' to input a new value at a specified position in the list.
Enter '5' to input a new value at the end of the list.
Enter '6' to input multiple new values at the end of the list.
Enter '7' to remove a specified value from the list by specifying its position in the list.
Enter '8' to remove the last value from the list.
Enter '9' to remove a specified value from the list.
Enter '10' to clear/ empty the list.
Enter '11' to display the list in reverse.
Enter '12' to display the list in a sorted manner, i.e. alphabetically ascending order (by default).
Enter '13' to display the list in alphabetically descending order.
Enter '14' to display the list.
Enter your choice: 3
The number of values in the list are: 5
Do you want to continue?
y
Enter '1' to create a list.
Enter '2' to display a specific range of the list.
Enter '3' to display the total number of values in the list.
Enter '4' to input a new value at a specified position in the list.
Enter '5' to input a new value at the end of the list.
Enter '6' to input multiple new values at the end of the list.
Enter '7' to remove a specified value from the list by specifying its position in the list.
Enter '8' to remove the last value from the list.
Enter '9' to remove a specified value from the list.
Enter '10' to clear/ empty the list.
Enter '11' to display the list in reverse.
Enter '12' to display the list in a sorted manner, i.e. alphabetically ascending order (by default).
Enter '13' to display the list in alphabetically descending order.
Enter '14' to display the list.
Enter your choice: 4
Enter the position in the list where you want to add a new value: 5
Input the value you wish to add in the list: Daksh
The list is now: ['Revanta', 'Disha', 'Amogh', 'Annanya', 'Shreya', 'Daksh']
Do you want to continue?
y
Enter '1' to create a list.
Enter '2' to display a specific range of the list.
Enter '3' to display the total number of values in the list.
Enter '4' to input a new value at a specified position in the list.
Enter '5' to input a new value at the end of the list.
Enter '6' to input multiple new values at the end of the list.
Enter '7' to remove a specified value from the list by specifying its position in the list.
Enter '8' to remove the last value from the list.
Enter '9' to remove a specified value from the list.
Enter '10' to clear/ empty the list.
Enter '11' to display the list in reverse.
Enter '12' to display the list in a sorted manner, i.e. alphabetically ascending order (by default).
Enter '13' to display the list in alphabetically descending order.
Enter '14' to display the list.
Enter your choice: 5
Type a value you want to add to the end of the list: Smrit
The list is now: ['Revanta', 'Disha', 'Amogh', 'Annanya', 'Shreya', 'Daksh', 'Smrit']
Do you want to continue?
y
Enter '1' to create a list.
Enter '2' to display a specific range of the list.
Enter '3' to display the total number of values in the list.
Enter '4' to input a new value at a specified position in the list.
Enter '5' to input a new value at the end of the list.
Enter '6' to input multiple new values at the end of the list.
Enter '7' to remove a specified value from the list by specifying its position in the list.
Enter '8' to remove the last value from the list.
Enter '9' to remove a specified value from the list.
Enter '10' to clear/ empty the list.
Enter '11' to display the list in reverse.
Enter '12' to display the list in a sorted manner, i.e. alphabetically ascending order (by default).
Enter '13' to display the list in alphabetically descending order.
Enter '14' to display the list.
Enter your choice: 6
Type the number of values you want to add to the end of the list: 2
Type a value you want to add to the end of the list: Armaghan
The list after adding the value(s) you specified to the end of the list is: ['Revanta', 'Disha',
'Amogh', 'Annanya', 'Shreya', 'Daksh', 'Smrit', 'Armaghan']
Type a value you want to add to the end of the list: Simran
The list after adding the value(s) you specified to the end of the list is: ['Revanta', 'Disha',
'Amogh', 'Annanya', 'Shreya', 'Daksh', 'Smrit', 'Armaghan', 'Simran']
Do you want to continue?
y
Enter '1' to create a list.
Enter '2' to display a specific range of the list.
Enter '3' to display the total number of values in the list.
Enter '4' to input a new value at a specified position in the list.
Enter '5' to input a new value at the end of the list.
Enter '6' to input multiple new values at the end of the list.
Enter '7' to remove a specified value from the list by specifying its position in the list.
Enter '8' to remove the last value from the list.
Enter '9' to remove a specified value from the list.
Enter '10' to clear/ empty the list.
Enter '11' to display the list in reverse.
Enter '12' to display the list in a sorted manner, i.e. alphabetically ascending order (by default).
Enter '13' to display the list in alphabetically descending order.
Enter '14' to display the list.
Enter your choice: 7
Type the index position of the value you wish to remove from the list: 5
The list after removing a value from the specified index position is: ['Revanta', 'Disha', 'Amogh',
'Annanya', 'Shreya', 'Smrit', 'Armaghan', 'Simran']
Do you want to continue?
y
Enter '1' to create a list.
Enter '2' to display a specific range of the list.
Enter '3' to display the total number of values in the list.
Enter '4' to input a new value at a specified position in the list.
Enter '5' to input a new value at the end of the list.
Enter '6' to input multiple new values at the end of the list.
Enter '7' to remove a specified value from the list by specifying its position in the list.
Enter '8' to remove the last value from the list.
Enter '9' to remove a specified value from the list.
Enter '10' to clear/ empty the list.
Enter '11' to display the list in reverse.
Enter '12' to display the list in a sorted manner, i.e. alphabetically ascending order (by default).
Enter '13' to display the list in alphabetically descending order.
Enter '14' to display the list.
Enter your choice: 8
The list after removing its last value is: ['Revanta', 'Disha', 'Amogh', 'Annanya', 'Shreya', 'Smrit',
'Armaghan']
Do you want to continue?
y
Enter '1' to create a list.
Enter '2' to display a specific range of the list.
Enter '3' to display the total number of values in the list.
Enter '4' to input a new value at a specified position in the list.
Enter '5' to input a new value at the end of the list.
Enter '6' to input multiple new values at the end of the list.
Enter '7' to remove a specified value from the list by specifying its position in the list.
Enter '8' to remove the last value from the list.
Enter '9' to remove a specified value from the list.
Enter '10' to clear/ empty the list.
Enter '11' to display the list in reverse.
Enter '12' to display the list in a sorted manner, i.e. alphabetically ascending order (by default).
Enter '13' to display the list in alphabetically descending order.
Enter '14' to display the list.
Enter your choice: 9
Type the exact value you want to remove from the list: Smrit
The list after removing the specified value is: ['Revanta', 'Disha', 'Amogh', 'Annanya', 'Shreya',
'Armaghan']
Do you want to continue?
y
Enter '1' to create a list.
Enter '2' to display a specific range of the list.
Enter '3' to display the total number of values in the list.
Enter '4' to input a new value at a specified position in the list.
Enter '5' to input a new value at the end of the list.
Enter '6' to input multiple new values at the end of the list.
Enter '7' to remove a specified value from the list by specifying its position in the list.
Enter '8' to remove the last value from the list.
Enter '9' to remove a specified value from the list.
Enter '10' to clear/ empty the list.
Enter '11' to display the list in reverse.
Enter '12' to display the list in a sorted manner, i.e. alphabetically ascending order (by default).
Enter '13' to display the list in alphabetically descending order.
Enter '14' to display the list.
Enter your choice: 11
The list in reverse is: ['Armaghan', 'Shreya', 'Annanya', 'Amogh', 'Disha', 'Revanta']
Do you want to continue?
y
Enter '1' to create a list.
Enter '2' to display a specific range of the list.
Enter '3' to display the total number of values in the list.
Enter '4' to input a new value at a specified position in the list.
Enter '5' to input a new value at the end of the list.
Enter '6' to input multiple new values at the end of the list.
Enter '7' to remove a specified value from the list by specifying its position in the list.
Enter '8' to remove the last value from the list.
Enter '9' to remove a specified value from the list.
Enter '10' to clear/ empty the list.
Enter '11' to display the list in reverse.
Enter '12' to display the list in a sorted manner, i.e. alphabetically ascending order (by default).
Enter '13' to display the list in alphabetically descending order.
Enter '14' to display the list.
Enter your choice: 12
The sorted list, i.e. in alphabetically ascending order is: ['Amogh', 'Annanya', 'Armaghan',
'Disha', 'Revanta', 'Shreya']
Do you want to continue?
y
Enter '1' to create a list.
Enter '2' to display a specific range of the list.
Enter '3' to display the total number of values in the list.
Enter '4' to input a new value at a specified position in the list.
Enter '5' to input a new value at the end of the list.
Enter '6' to input multiple new values at the end of the list.
Enter '7' to remove a specified value from the list by specifying its position in the list.
Enter '8' to remove the last value from the list.
Enter '9' to remove a specified value from the list.
Enter '10' to clear/ empty the list.
Enter '11' to display the list in reverse.
Enter '12' to display the list in a sorted manner, i.e. alphabetically ascending order (by default).
Enter '13' to display the list in alphabetically descending order.
Enter '14' to display the list.
Enter your choice: 13
The sorted list, i.e. in alphabetically descending order is: ['Shreya', 'Revanta', 'Disha',
'Armaghan', 'Annanya', 'Amogh']
Do you want to continue?
y
Enter '1' to create a list.
Enter '2' to display a specific range of the list.
Enter '3' to display the total number of values in the list.
Enter '4' to input a new value at a specified position in the list.
Enter '5' to input a new value at the end of the list.
Enter '6' to input multiple new values at the end of the list.
Enter '7' to remove a specified value from the list by specifying its position in the list.
Enter '8' to remove the last value from the list.
Enter '9' to remove a specified value from the list.
Enter '10' to clear/ empty the list.
Enter '11' to display the list in reverse.
Enter '12' to display the list in a sorted manner, i.e. alphabetically ascending order (by default).
Enter '13' to display the list in alphabetically descending order.
Enter '14' to display the list.
Enter your choice: 14
The current list is: ['Shreya', 'Revanta', 'Disha', 'Armaghan', 'Annanya', 'Amogh']
Do you want to continue?
y
Enter '1' to create a list.
Enter '2' to display a specific range of the list.
Enter '3' to display the total number of values in the list.
Enter '4' to input a new value at a specified position in the list.
Enter '5' to input a new value at the end of the list.
Enter '6' to input multiple new values at the end of the list.
Enter '7' to remove a specified value from the list by specifying its position in the list.
Enter '8' to remove the last value from the list.
Enter '9' to remove a specified value from the list.
Enter '10' to clear/ empty the list.
Enter '11' to display the list in reverse.
Enter '12' to display the list in a sorted manner, i.e. alphabetically ascending order (by default).
Enter '13' to display the list in alphabetically descending order.
Enter '14' to display the list.
Enter your choice: 10
The removed list is: []
Do you want to continue?
n
# Q.6:
# Enter a list of size 'n' and shift all the even numbers at the start of the list and all the odd
numbers to
# the last/ end of the list.
INPUT:
l = []
le = []
lo = []
n = int(input("Please enter the size of the list: "))
if type(n) == int:
for i in range(n):
e = int(input("Enter a number you wish to add: "))
l.append(e)
print("The inputted list was:")
print(l)
else:
print("Please enter a valid input.")
for j in l:
if j%2 == 0:
le.append(j)
else:
lo.append(j)
l = le + lo
print("The output list is:")
print(l)
OUTPUT:
Please enter the size of the list: 10
Enter a number you wish to add: 190
Enter a number you wish to add: -12412
Enter a number you wish to add: 9092
Enter a number you wish to add: -1213
Enter a number you wish to add: 3419
Enter a number you wish to add: -942
Enter a number you wish to add: 801
Enter a number you wish to add: -32
Enter a number you wish to add: 1
Enter a number you wish to add: -0943
The inputted list was:
[190, -12412, 9092, -1213, 3419, -942, 801, -32, 1, -943]
The output list is:
[190, -12412, 9092, -942, -32, -1213, 3419, 801, 1, -943]
# Q.7:
# Enter a:
# (i) Numeric list.
# (ii) String/ Alphanumeric.
# Count the number of occurrences and store as dictionary (value as a key and the number of
occurrences as a key value.
INPUT:
l = []
n = int(input("Enter the size of the list you wish to create: "))
for i in range(n):
e = input("Enter a value to add in the list: ")
l += e
# Or l.append(e)
print("The list is: ")
print(l)
d = {}
for j in l:
if j not in d:
d[j] = l.count(j)
print("Therefore, the dictionary with number of occurrences of each character is: ")
print(d)
OUTPUT:
Enter the size of the list you wish to create: 5
Enter a value to add in the list: 45
Enter a value to add in the list: 87
Enter a value to add in the list: 231
Enter a value to add in the list: 098
Enter a value to add in the list: 34
The list is:
['4', '5', '8', '7', '2', '3', '1', '0', '9', '8', '3', '4']
Therefore, the dictionary with number of occurrences of each character is:
{'4': 2, '5': 1, '8': 2, '7': 1, '2': 1, '3': 2, '1': 1, '0': 1, '9': 1}
# Q.8:
# Enter a numeric list of size 'n', shift all the positive values to the beginning of the list and all
the
# negative values to the end of the list.
INPUT:
l = []
l1 = []
n = int(input("Enter the size of the list you wish to create: "))
for i in range(n):
u = int(input("Enter a non-zero number you wish to add to your list: "))
if u == 0:
print("Please input a non-zero number.")
else:
l.append(u)
print("The list was: \n", l)
for k in range(len(l)):
if l[k] > 0:
l1.insert(0, l[k])
elif l[k] < 0:
l1.insert(len(l), l[k])
print("The modified list is: \n", l1)
OUTPUT:
Enter the size of the list you wish to create: 10
Enter a non-zero number you wish to add to your list: -231
Enter a non-zero number you wish to add to your list: 4135
Enter a non-zero number you wish to add to your list: -5942
Enter a non-zero number you wish to add to your list: 21323
Enter a non-zero number you wish to add to your list: -532
Enter a non-zero number you wish to add to your list: 123
Enter a non-zero number you wish to add to your list: -653
Enter a non-zero number you wish to add to your list: 4245
Enter a non-zero number you wish to add to your list: -991
Enter a non-zero number you wish to add to your list: 2123
The list was:
[-231, 4135, -5942, 21323, -532, 123, -653, 4245, -991, 2123]
The modified list is:
[2123, 4245, 123, 21323, 4135, -231, -5942, -532, -653, -991]
# Q.9:
# Enter a list of size 'n'. Display the list element thrice if it is a number and display the element
# terminated with a ’#', if it is not a number.
INPUT:
l = []
n = int(input("Enter the size of the list: "))
for i in range(n):
u = input("Enter an element you wish to add: ")
l.append(u)
for s in l:
if s.isdigit():
print("Since this value is an integer, the output is: ")
for k in range(3):
print(s)
else:
print("Since this value is not an integer, the output is: ")
print(s, "#")
OUTPUT:
Enter the size of the list: 10
Enter an element you wish to add: 2342
Enter an element you wish to add: Revanta
Enter an element you wish to add: Amogh
Enter an element you wish to add: 9389
Enter an element you wish to add: Annanya
Enter an element you wish to add: -9812
Enter an element you wish to add: Shreya
Enter an element you wish to add: 667
Enter an element you wish to add: Disha
Enter an element you wish to add: 0
Since this value is an integer, the output is:
2342
2342
2342
Since this value is not an integer, the output is:
Revanta #
Since this value is not an integer, the output is:
Amogh #
Since this value is an integer, the output is:
9389
9389
9389
Since this value is not an integer, the output is:
Annanya #
Since this value is an integer, the output is:
-9812
-9812
-9812
Since this value is not an integer, the output is:
Shreya #
Since this value is an integer, the output is:
667
667
667
Since this value is not an integer, the output is:
Disha #
Since this value is an integer, the output is:
0
0
0
# Q.10:
# Write a Python Program to implement stack operations on a numerical list.
INPUT:
def isempty(stack):
if len(stack) <= 0:
print("Yes")
return True
else:
print("No")
return False
def push(val, stack):
stack.append(val)
def pop(stack):
if isempty is True:
print("Stack is empty.")
else:
e = stack.pop()
print(f”{e} is removed from the stack.")
def display(stack):
print("The stack is, ", stack)
def main():
c = 'y'
st = []
while c == 'y':
print("Type: 1. for Push, 2. for Pop and 3. for Display.")
ch = int(input("Enter your choice: "))
if ch == 1:
ele = input("Enter the element you want to add: ")
push(ele, st)
elif ch == 2:
pop(st)
elif ch == 3:
display(st)
else:
print("Invalid option.")
c = input("Do you want to continue? Y or N:\n")
main()
OUTPUT:
Type: 1. for Push, 2. for Pop and 3. for Display.
Enter your choice: 1
Enter the element you want to add: Revanta
Do you want to continue? y
Type: 1. for Push, 2. for Pop and 3. for Display.
Enter your choice: 1
Enter the element you want to add: Disha
Do you want to continue? y
Type: 1. for Push, 2. for Pop and 3. for Display.
Enter your choice: 1
Enter the element you want to add: Amogh
Do you want to continue? y
Type: 1. for Push, 2. for Pop and 3. for Display.
Enter your choice: 1
Enter the element you want to add: Annanya
Do you want to continue? y
Type: 1. for Push, 2. for Pop and 3. for Display.
Enter your choice: 1
Enter the element you want to add: Shreya
Do you want to continue? y
Type: 1. for Push, 2. for Pop and 3. for Display.
Enter your choice: 1
Enter the element you want to add: Smrit
Do you want to continue? y
Type: 1. for Push, 2. for Pop and 3. for Display.
Enter your choice: 2
Smrit is removed from the stack.
Do you want to continue? y
Type: 1. for Push, 2. for Pop and 3. for Display.
Enter your choice: 3
The stack is, ['Revanta', 'Disha', 'Amogh', 'Annanya', 'Shreya']
Do you want to continue? n
# Q.11:
# Write a Python Program to create a stack called 'student' with roll number, name, total
marks, as values. Perform stack
# implementation to add (push), delete (pop) and display the student details.
INPUT:
def isempty(st):
if len(st) == 0:
print("Yes")
return True
else:
print("No")
return False
def push(st):
r = input("Enter roll number of student: ")
n = input("Enter name of student: ")
tot = input("Enter total marks obtained by student: ")
st.append(r)
st.append(n)
st.append(tot)
def pop(st):
if isempty is True:
print("Stack is empty.")
else:
e = st.pop()
print(f"The list value you inputted last, i.e. {e}, has been removed from the student's
detail.")
def display(st):
print(f"The student's details are: {st}")
def main():
c = 'y'
st = []
while c == 'y' or c == 'Y':
print("Type: 1. For Push, 2. For Pop and 3. For Display.")
ch = int(input("Enter your choice: "))
if ch == 1:
push(st)
elif ch == 2:
pop(st)
elif ch == 3:
display(st)
else:
print("Invalid option.")
c = input("Do you want to continue?\n")
main()
OUTPUT:
Type: 1. For Push, 2. For Pop and 3. For Display.
Enter your choice: 1
Enter roll number of student: 42
Enter name of student: Revanta
Enter total marks obtained by student: 100
Do you want to continue?
y
Type: 1. For Push, 2. For Pop and 3. For Display.
Enter your choice: 1
Enter roll number of student: 11
Enter name of student: Disha
Enter total marks obtained by student: 99
Do you want to continue?
y
Type: 1. For Push, 2. For Pop and 3. For Display.
Enter your choice: 1
Enter roll number of student: 8
Enter name of student: Amogh
Enter total marks obtained by student: 98
Do you want to continue?
y
Type: 1. For Push, 2. For Pop and 3. For Display.
Enter your choice: 1
Enter roll number of student: 14
Enter name of student: Annanya
Enter total marks obtained by student: 97
Do you want to continue?
y
Type: 1. For Push, 2. For Pop and 3. For Display.
Enter your choice: 1
Enter roll number of student: 32
Enter name of student: Shreya
Enter total marks obtained by student: 96
Do you want to continue?
y
Type: 1. For Push, 2. For Pop and 3. For Display.
Enter your choice: 1
Enter roll number of student: 50
Enter name of student: Smrit
Enter total marks obtained by student: 95
Do you want to continue?
y
Type: 1. For Push, 2. For Pop and 3. For Display.
Enter your choice: 2
The list value you inputted last, i.e. 95, has been removed from the student's detail.
Do you want to continue?
y
Type: 1. For Push, 2. For Pop and 3. For Display.
Enter your choice: 3
The student's details are: ['42', 'Revanta', '100', '11', 'Disha', '99', '8', 'Amogh', '98', '14',
'Annanya', '97', '32', 'Shreya', '96', '50', 'Smrit']
Do you want to continue?
n
# Q.12:
# Display e-names and e-numbers of all employees in the I.T. Department. Display the e-names
and
# e-numbers of all employees, whose salaries are in the range of ₹50,000 to ₹75,000.
INPUT:
OUTPUT:
# Q.13:
# Create a stack named 'employee', with e-number and e-names as values. Write the following
functions:
# (i) Pop.
# (ii) Push
# (iii) Display
INPUT:
def main():
c = 'y'
emp = []
while c == 'y':
b = int(input("Press 1. For Pop, 2. For Push and 3. For Display: "))
if b == 1:
pop(emp)
elif b == 2:
push(emp)
elif b == 3:
display(emp)
else:
print("Invalid Option.")
c = input("Do you want to continue?\n")
def pop(emp):
if len(emp) == 0:
print("Stack is empty.")
else:
emp.pop()
def push(emp):
eno = int(input("Enter employee's roll number: "))
ena = input("Enter employee's name: ")
le = (eno, ena)
emp.append(le)
def display(emp):
print(f"The requested stack is:{emp}")
main()
OUTPUT:
Press 1. For Pop, 2. For Push and 3. For Display: 2
Enter employee's roll number: 29805
Enter employee's name: Revanta
Do you want to continue?
y
Press 1. For Pop, 2. For Push and 3. For Display: 2
Enter employee's roll number: 11093
Enter employee's name: Disha
Do you want to continue?
y
Press 1. For Pop, 2. For Push and 3. For Display: 2
Enter employee's roll number: 76621
Enter employee's name: Amogh
Do you want to continue?
y
Press 1. For Pop, 2. For Push and 3. For Display: 2
Enter employee's roll number: 59929
Enter employee's name: Annanya
Do you want to continue?
y
Press 1. For Pop, 2. For Push and 3. For Display: 2
Enter employee's roll number: 66719
Enter employee's name: Shreya
Do you want to continue?
y
Press 1. For Pop, 2. For Push and 3. For Display: 2
Enter employee's roll number: 44559
Enter employee's name: Smrit
Do you want to continue?
y
Press 1. For Pop, 2. For Push and 3. For Display: 1
Do you want to continue?
y
Press 1. For Pop, 2. For Push and 3. For Display: 3
The requested stack is: [(29805, 'Revanta'), (11093, 'Disha'), (76621, 'Amogh'), (59929,
'Annanya'), (66719, 'Shreya')]
Do you want to continue?
n
# Q.14:
#
INPUT:
OUTPUT:
# Q.15:
# Write a Python Program to enter data for a student into a file.
# (i) Roll Number of Student.
# (ii) Name of Student.
# (iii) Class of Student.
# (iv) Total Marks Obtained by Student.
INPUT:
# Q.15:
# Write a Python Program to enter data for a student into a file.
# (i) Roll Number of Student.
# (ii) Name of Student.
# (iii) Class of Student.
# (iv) Total Marks Obtained by Student.
f1 = open("Q_15.txt", 'a')
rno = input("Enter the Roll Number of the Student: ")
nm = input("Enter the Full Name of the Student: ")
cls = input("Enter the Class of the Student: ")
sec = input("Enter the Section of the Student: ")
mks = input("Enter the Total Marks Obtained by the Student: ")
print("\n")
l1 = ["Details of the Student:\n", "\n", "Roll Number of the Student: ", rno, "\n", "Full Name of
the Student: ", nm, "\n", "Class of the Student: ", cls, "\n", "Section of the Student: ", sec, "\n",
"Total Marks obtained by the Student: ", mks, '\n', '\n', '\n']
f1.writelines(l1)
f1.close()
OUTPUT:
Enter the Roll Number of the Student: 11
Enter the Full Name of the Student: Amogh Chary
Enter the Class of the Student: 12
Enter the Section of the Student: B
Enter the Total Marks Obtained by the Student: 99
# Q.16:
# Write a Python Program to enter data for 'n' number of students into a file.
# (i) Roll Number of Student.
# (ii) Name of Student.
# (iii) Class of Student.
# (iv) Total Marks Obtained by Student.
INPUT:
f1 = open("Q_16.txt", 'a')
n = int(input("Enter the number of students: "))
l2 = []
for i in range(n):
rno = input("Enter the roll number of a student: ")
nm = input("Enter the full name of that student: ")
cls = input("Enter the class of that student: ")
sec = input("Enter the section of that student: ")
mks = input("Enter the total marks obtained by that student: ")
print("\n")
l1 = ["Details of Student:\n", "\n", "Roll Number of Student: ", rno, "\n", "Full Name of
Student: ", nm, "\n", "Class of Student: ", cls, "\n", "Section of Student: ", sec, "\n", "Total Marks
obtained by Student: ", mks, "\n", "\n", ‘\n’]
l2 = l2 + l1
f1.writelines(l2)
f1.close()
OUTPUT:
Enter the number of students: 5
Enter the roll number of a student: 1
Enter the full name of that student: Amogh Chary
Enter the class of that student: 12
Enter the section of that student: C
Enter the total marks obtained by that student: 99
INPUT:
f1 = open("Q_17.txt", 'a')
c = 'y'
l2 = []
while c == 'y':
text = input("Enter text: ")
l1 = [text, "\n"]
l2 = l2 + l1
c = input("To continue, press 'y': ")
f1.writelines(l2)
f1.close()
OUPUT:
Enter text: My friends' names are: Disha Aswal, Amogh Chary, Annanya Kumar, Smrit Singh and
Shreya Sharma!
To continue, press 'y': y
Enter text: I want to be a Computer Science Engineer from a very good Software Engineering
college in India.
To continue, press 'y': n
# Q.18:
# Write a Python Program to open a file and display it using ‘.read()’. Also read 10 bytes/
# characters at a time.
INPUT:
f1 = open("Q_18.txt", 'a')
str = input("Write text in document: \n")
f2 = f1.writelines(str)
f1.close()
f3 = open("Q_18.txt", 'r')
str1 = f3.read()
print("Contents of the file are: Q_18.txt")
str2 = f3.read(10)
while True:
print(str2)
print("")
print("File reading is complete.")
f3.close()
OUTPUT:
# Q.19:
# Write a Python Program to count the number of lines and display it in the given format:
# Count and display the number of characters in each line, total percentage of characters in
each line.
INPUT:
f1 = open("Q_19.txt", 'r')
s = ""
tc, lc, cc = 0, 0, 0
while s:
lc += 1
s = f1.readlines()
cc = len(s)
print(lc, '.', s, 'Size: ', cc)
tc += cc
f1.close()
print("Total lines: ", lc, "\n", "Total characters: ", tc)
OUTPUT:
# Q.20:
# Count the number of lines starting with 'I' or 'i' in a file.
INPUT:
f1 = open("Q_20.txt", 'w')
str = input("Write text in document: \n")
f2 = f1.writelines(str)
f3 = open("Q_20.txt", 'r')
count = 0
ls = f3.readlines()
for i in range(len(ls)):
if ls[i][0] == 'I' or 'i':
count += 1
print(f"Number of lines beginning with 'I' or 'i': {count}”)
OUTPUT:
# Q.21: Write a Python Program using ‘readlines()’ to read the contents of the text file
“Q_21.txt”.
# (i) Display a line at a time.
# (ii) Display the contents of a line at a time.
# (iii) Count the number of lines.
# (iv) Count the number of characters in each time.
# (v) Total number of characters in the file.
# (vi) Count and display the number of lines beginning with ‘I’ or ‘i’.
INPUT:
f1 = open("Q_21.txt", 'r')
count = 0
ls = f1.readlines()
tcc = 0
for i in range(len(ls)):
print(i + 1, '.', '\n', ls[i], 'Size:', len(ls[i]))
print("\n")
cc = len(ls[i])
tcc += cc
if ls[i][0] == 'I':
count += 1
print(f"\nNumber of lines beginning with 'I': {count}”)
print("Total number of characters: ", tcc)
print("Total number of lines: ", len(ls))
OUTPUT:
# Q.22:
# Create a file 'Q_22.txt' with its contents as:
# "Jack and Jill
# went up the hill
# Baa baa black sheep
# Have you any wool?
# Yes Sir, Yes Madam
# Three Bags Full!!"
# (i) Read and display the number of words in each line.
# (ii) Display only those lines which have four words in them.
# (iii) Count and display the number of occurrences of the letter 'e' in the file.
# (iv) Display only those words that are a palindrome.
# (v) Display the contents of the file with each word separated by a "#".
INPUT:
f1 = open("Q_22.txt", 'w')
str = '''Jack and Jill
went up the hill
Baa baa black sheep
Have you any wool?
Yes Sir, Yes Madam
Three Bags Full!!'''
f1.write(str)
f1.close()
f2 = open("Q_22.txt", 'r')
ls = f2.readlines()
print("Answer of (i) is: \n")
count = 0
for i in ls:
j = i.split()
count += 1
print("The number of words in sentence ", count, " of the file is: ", len(j))
print("\n")
print("Answer of (ii) is: \n")
print("The lines which only have four words in them are: \n")
o=0
for i0 in ls:
j0 = i0.split()
if len(j0) == 4:
o += 1
print(o, ": ", i0)
print("")
print("Answer of (iii) is: \n")
print("The following words have the letter 'e' in them: \n")
count0 = 0
for i1 in ls:
for j1 in i1:
if j1 == "e":
count0 += 1
for i2 in ls:
j2 = i2.split()
for l in j2:
for m in l:
if m == 'e':
print(l)
print("")
print("The number of occurrences of 'e' in the given file, Q_22.txt, is: ", count0)
print("\n")
print("The answer to (iv) is: \n")
def ispalindrome(l):
return l == l[::-1]
for i3 in ls:
j3 = i3.split()
for l in j3:
ans = ispalindrome(l)
if ans:
print("A palindromic word from the file is: ", l)
print("If there were no palindromic words in the file, the result must have been blank list.")
print('\n')
print("The answer to (v) is: \n")
for i4 in ls:
j4 = i4.split()
for l in j4:
print(l, end='#')
f2.close()
OUTPUT:
# Q.23:
# Creating a .csv file in Python using 'writerow()' function.
INPUT:
import csv
fobj = open("student.csv", 'w', newline='')
fcsv = csv.writer(fobj)
fcsv.writerow(['Roll Number'.center(101, " "), 'Name'.center(100, " "), 'English'.center(101, " "),
'Physics'.center(101, " "),
'Chemistry'.center(101, " "), 'Mathematics'.center(101, " "), 'Computer
Science'.center(100, " "),
'Total'.center(101, " "), 'Percentage'.center(100, " ")])
n = int(input("Enter the number of records you want to save: "))
for i in range(n):
rno = int(input("Enter roll number: "))
nm = input("Enter name: ")
eng = float(input("Enter English marks out of 100: "))
phy = float(input("Enter Physics marks out of 100: "))
chem = float(input("Enter Chemistry marks out of 100: "))
math = float(input("Enter Mathematics marks out of 100: "))
cs = float(input("Enter Computer Science marks out of 100: "))
tot = eng + phy + chem + math + cs
per = tot/5
fcsv.writerow([str(rno).center(len(str(rno)) + 100, " "), str(nm).center(len(str(rno)) + 100, " "),
str(eng).center(len(str(rno)) + 100, " "), str(phy).center(len(str(rno)) + 100, " "),
str(chem).center(len(str(rno)) + 100, " "), str(math).center(len(str(rno)) + 100, " "),
str(cs).center(len(str(rno)) + 100, " "), str(tot).center(len(str(rno)) + 100, " "),
str(per).center(len(str(rno)) + 100, " ")])
fobj.close()
OUTPUT:
# Q.24:
# Creating a .csv file in Python using 'writerows()' function and then reading through the
'reader()'
# function.
INPUT:
import csv
fobj = open("student1.csv", 'a', newline='')
fcsv = csv.writer(fobj)
stl = []
ch = 'y'
fcsv.writerow(['Roll Number', 'Name', 'English', 'Physics', 'Chemistry', 'Mathematics', 'Computer
Science', 'Total', 'Percentage'])
while ch == 'y':
rno = int(input("Enter roll number: "))
nm = input("Enter name: ")
eng = float(input("Enter English marks out of 100: "))
phy = float(input("Enter Physics marks out of 100: "))
chem = float(input("Enter Chemistry marks out of 100: "))
math = float(input("Enter Mathematics marks out of 100: "))
cs = float(input("Enter Computer Science marks out of 100: "))
tot = eng + phy + chem + math + cs
per = tot/5
l = [rno, nm, eng, phy, chem, math, cs, tot, per]
stl.append(l)
ch = input("To continue inputting more data, press 'y' or 'Y': ")
fcsv.writerows(stl)
fobj.close()
fobj1 = open("student.csv", 'r')
fcsv1 = csv.reader(fobj1)
ask = input("To see your data, press 'y' or 'Y': ")
while ask == 'y' or ask == 'Y':
for rec in fcsv1:
print(rec)
fobj1.close()
OUTPUT:
# Q.51:
# Writing in a binary file using '.dump()' function.
INPUT:
import pickle
with open("Q_51.dat", 'wb') as fw:
ch = 'y'
ctr = 1
while ch == 'y' or ch == 'Y':
rno = int(input("Enter roll number of student: "))
nm = input("Enter name of student: ")
tot_m = float(input("Enter marks of student out of 100: "))
lst = [rno, nm, tot_m]
ctr += 1
pickle.dump(lst, fw)
ch = input("Do you want to continue to add more records? Y or N:\n")
print(f"{ctr} Records written in file student.")
OUTPUT:
Enter roll number of student: 42
Enter name of student: Revanta Choudhary
Enter marks of student out of 100: 89
Do you want to continue to add more records? Y or N:
Y
Enter roll number of student: 11
Enter name of student: Amogh Chary
Enter marks of student out of 100: 99
Do you want to continue to add more records? Y or N:
Y
Enter roll number of student: 8
Enter name of student: Disha Aswal
Enter marks of student out of 100: 85
Do you want to continue to add more records? Y or N:
Y
Enter roll number of student: 45
Enter name of student: Annanya Kumar
Enter marks of student out of 100: 75
Do you want to continue to add more records? Y or N:
Y
Enter roll number of student: 50
Enter name of student: Shreya Sharma
Enter marks of student out of 100: 59
Do you want to continue to add more records? Y or N:
N
# Q.52:
# Reading and displaying a binary file.
INPUT:
import pickle
with open("Q_51.dat", 'rb') as fr:
lst = []
ctr = 0
try:
while True:
lst = pickle.load(fr)
print(lst)
ctr += 1
except EOFError:
print(f"{ctr} Records have been read and displayed.")
try:
print(["Roll Number", "Name", "Total Marks"])
while True:
lst1 = pickle.load(fr)
for i in lst1:
print(i, "\t", end='')
print()
ctr += 1
except:
pass
OUTPUT:
# Q.53:
# Searching for specified values in a binary file.
INPUT:
import pickle
with open("Q_51.dat", 'rb') as fr:
l = []
ctr = 0
try:
while True:
l = pickle.load(fr)
if l[3] >= 75:
for i in l:
print(i, "\t", end='')
ctr += 1
print()
except EOFError:
print(f"{ctr} Matches found.")
OUTPUT:
# Q.54:
# Read a record from the file "Q_51.dat". Display the file pointer position and the record detail
using
# functions '.tell()' and '.seek()'.
INPUT:
import pickle
with open("Q_51.dat", 'rb') as fr:
st = []
try:
while True:
pos = fr.tell()
st = pickle.load(fr)
print(pos, st)
except EOFError:
print(f"File reading is complete, {fr.tell()} bytes are occupied.")
OUTPUT:
# Q.55:
# Update a specified value in a binary file.
INPUT:
import pickle
with open("Q_51.dat", 'rb+') as fr:
nm = input("Enter student name to update: ")
st = []
status = False
try:
while True:
pos = fr.tell()
st = pickle.load(fr)
if st[1] == nm:
n = float(input("Enter updated marks: "))
st[3] = n
fr.seek(pos)
pickle.dump(st, fr)
status = True
except EOFError:
if status := True:
print("Recorded and updated successfully.")
else:
print("No match found.")
OUTPUT:
# Q.56:
# Deleting a specified value from a binary file.
INPUT:
import pickle
import os
lst = []
with open("Q_51.dat", 'rb') as fr:
with open("temp.dat", 'wb') as ft:
rno = int(input("Enter roll number to be deleted: "))
try:
while True:
lst = pickle.load(fr)
if rno == lst[0]:
pass
else:
pickle.dump(lst, ft)
except EOFError:
print("Deletion complete.")
os.remove(lst[0])
os.rename('temp.dat', 'Q_51.dat')
OUTPUT: