In: Computer Science
Implement function get_contact(contacts, name) that returns a string. The contacts and the name parameter are both type string. This function checks for the name string in the contacts string and returns that person’s contact information. If the person is not found, the function returns, “name not in contact”. Assume input is always valid. Assume the same name is not repeated in contacts.
[You may use split(), range(), len() ONLY and no other built-in function or method]
Examples:
contacts = “Frank 703-222-2222 Sue 703-111-1111 Jane 703-333-3333”
name = “Sue”
print(get_contact(contacts, name))
returns:
703-111-1111
name = “Sam”
print(get_contact(contacts, name))
returns:
name not in contact
CODE WITH EXPLANATION:
def get_contact(contacts,name):#function definition withrequired parameters
con_lis=contacts.split( )#splits the string with space as separator and stores the value in list named con_list
for x in range(len(con_lis)):#a for loop that runs 0 to the length of the list
if con_lis[x] == name:#if contact name is found in list
contact=con_lis[x+1]#the contact detail is next to the name hence X+1
break#breaks the loop as the contact is found
else:#in case not found
contact="name not in contact"#stores this value in the conatct
return contact #finally returns the contact
contacts = input("Enter Contacts ")#"Frank 703-222-2222 Sue 703-111-1111 Jane 703-333-3333"
name =input("Enter Name ")#to receive input on console
print(get_contact(contacts,name)) #print the contact
OUTPUT: