Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
134k views
in Computer by (54.6k points)
closed by

Write a Python program to input ‘n’names and phone numbers to store it in a dictionary and to search and print the phone number of that particular name.

2 Answers

+2 votes
by (3.7k points)
selected by
 
Best answer

Here's a Python program that allows the user to input n names and phone numbers and stores them in a dictionary. The program then allows the user to search for a particular name and prints its corresponding phone number if it exists in the dictionary:

# Initialize an empty dictionary to store names and phone numbers
phonebook = {}

# Ask the user for the number of entries to input
n = int(input("Enter the number of entries: "))

# Loop through n entries to input names and phone numbers
for i in range(n):
    name = input("Enter a name: ")
    phone = input("Enter a phone number: ")
    phonebook[name] = phone

# Ask the user for a name to search
search_name = input("Enter a name to search: ")

# Search for the name in the phonebook dictionary
if search_name in phonebook:
    print(f"{search_name}'s phone number is {phonebook[search_name]}")
else:
    print(f"{search_name} is not in the phonebook")

Example Output of the Program:

Enter the number of entries: 3
Enter a name: John
Enter a phone number: 555-1234
Enter a name: Sarah
Enter a phone number: 555-5678
Enter a name: Mike
Enter a phone number: 555-9101
Enter a name to search: Sarah
Sarah's phone number is 555-5678
+1 vote
by (89.9k points)
edited by
phonebook = {}
n = int(input("Enter total number of friends to create a telephone book: "))

for i in range(n):
    name = input("Enter name: ")
    phone = input("Enter phone number: ")
    phonebook[name] = phone

search_name = input("Enter friend's name to search for: ")
found = False

for name in phonebook:
    if name == search_name:
        print("Phone number = ", phonebook[name])
        found = True

if not found:
    print("Given name does not exist")

Example Output:

Enter total number of friends to create a telephone book: 3
Enter name: John
Enter phone number: 555-1234
Enter name: Sarah
Enter phone number: 555-5678
Enter name: Mike
Enter phone number: 555-9101
Enter friend's name to search for: Sarah
Phone number =  555-5678

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...