Question 35(1)
30 March 2023 · Computer Science (083)
Shreyas is a programmer who has been given the task of writing a function write_bin() to create a binary file Cust_file.dat containing customer records — customer number (c_no), name (c_name), quantity (qty), price (price) and amount (amt).
The function accepts c_no, c_name, qty and price. If qty is less than 10, it prints 'Quantity less than 10 ..... Cannot SAVE'. Otherwise it computes amt = price * qty and writes the record (as a list) to the binary file.
import pickle
def write_bin():
bin_file = __________ # Statement 1
while True:
c_no = int(input("enter customer number"))
c_name = input("enter customer name")
qty = int(input("enter qty"))
price = int(input("enter price"))
if __________ : # Statement 2
print("Quantity less than 10..Cannot SAVE")
else:
amt = price * qty
c_detail = [c_no, c_name, qty, price, amt]
__________ # Statement 3
ans = input("Do you wish to enter more records y/n")
if ans.lower() == 'n':
__________ # Statement 4
______________ # Statement 5
______________ # Statement 6Answer the following : (i) Write the correct Statement 1 to open 'Cust_file.dat' for writing. (ii) Write Statement 2 to check whether qty is less than 10. (iii) Write Statement 3 to write data to the binary file and Statement 4 to stop further processing if the user does not wish to enter more records.
Answer
(i) Statement 1 —
bin_file = open("Cust_file.dat", "wb")("ab" mode is also accepted.)
(ii) Statement 2 —
qty < 10(iii) Statement 3 —
pickle.dump(c_detail, bin_file)Statement 4 —
breakExplanation
Statement 1 opens the file in binary-write mode. Statement 2 is the condition that flags a too-small quantity. Statement 3 serialises the record list to the binary file with pickle.dump. Statement 4 exits the while loop when the user has no more records to enter.