The purpose of the following Python function is to search the details of a…

2026

The purpose of the following Python function is to search the details of a person in a binary file named contact.dat. The file stores records containing the Name, Address, Phone Number, and Email ID of multiple contacts. The function receives a person’s name as an argument and searches the file to display the corresponding contact details if the name matches. However, some parts of the program are missing. You are required to fill in the missing code segments labeled Blank A, Blank B, Blank C, and Blank D, so that the function performs its intended operation correctly.

_____ Blank A _____                   # Line 01

def search_contact(Name):             # Line 02
    Found = False                    # Line 03
    try:
        _____ Blank B _____ as File:  # Line 04
            while True:              # Line 05
                try:
                    Data = _____ Blank C _____   # Line 06
                    if _____ Blank D _____:      # Line 07
                        print("Name:", Data[0])  # Line 08
                        print("Address:", Data[1])  # Line 09
                        print("Phone:", Data[2])    # Line 10
                        print("Email:", Data[3])    # Line 11
                        Found = True               # Line 12
                        break                     # Line 13
                except EOFError:                  # Line 14
                    break
            if not Found:                         # Line 15
                print("Contact not found.")       # Line 16
    except FileNotFoundError:                    # Line 17
        print("Error! The file does not exist.") # Line 18

(A) Write the missing code for Blank A to import the required module for processing binary files in Python.

(B) Write the missing code for Blank B to open the binary file contact.dat in the appropriate mode.

(C) Write the missing code for Blank C to read one record from the binary file.

(D) Write the missing code for Blank D to correctly compare the name entered by the user.

Show answer & explanation

To correctly search records from a binary file, the missing code segments should be filled as follows:

Blank A:

import pickle

Blank B:

open("contact.dat", "rb")

Blank C:

pickle.load(File)

Blank D:

Data[0] == Name

Complete Explanation:

  • pickle module is required to read (deserialize) objects from a binary file.

  • File is opened in read-binary mode ("rb").

  • pickle.load() reads one record at a time from the file.

  • Each record is assumed to be a list: [Name, Address, Phone, Email].

  • Condition Data[0] == Name checks whether the given name matches the stored record.

Answer (All Blanks):

  • Blank A: import pickle

  • Blank B: open("contact.dat", "rb")

  • Blank C: pickle.load(File)

  • Blank D: Data[0] == Name

Explore the full course: Hpsc Pgt Computer Science