Page 432 - Computer Science Class 11 With Functions
P. 432

Return Value:

                     True: if key is found in the list, False otherwise
                     index:
                         if search succeeds, index of search key found
                         None, if search fails

                 '''
                 found = False
                 for index in range(len(myList)):
                     if myList[index] == key:
                         found = True
                         return found, index

                 return found, None


             myList = []
             numElements = int(input("Enter size of the list: "))

             print("Enter each element and press enter: ")
             for i in range(0, numElements):   #list input element-wise
                 num = int(input())
                 myList.append(num)
             print("Contents of list:", myList)
             while True:

                 key = int(input("Enter the number to be searched:"))
                 found, index = search(myList, key)
                 if found:
                     print("Element",key," is present in the list at index ", index)

                 else:
                     print("Element",key," is not present in the list")
                 searchAgain = input("Continue another search? say Y/y for yes, N/n for no:")
                 if searchAgain != "Y" and searchAgain != "y":
                     break
        Program 16

        Write a function search that takes a tuple myTuple and a value key to be searched in myTuple as arguments.
        When the key is present in myTuple, the function search returns True and the index where the search key
        is found. If search reaches the end of the tuple without finding the key, search returns False with None as the
        index. Invoke search to search for a key in a tuple provided by the user.

        Ans. def search(myTuple, key):
                 """

                 Objective: To search the key in myTuple
                 Input Parameters:
                     myTuple: tuple


         430   Touchpad Computer Science-XI
   427   428   429   430   431   432   433   434   435   436   437