Page 299 - Computer Science Class 11 Without Functions
P. 299
If it reaches the end of the list without finding the key, the program returns False.
Program 12.1: Linear Search
01 '''
02 Objective: To search for a key in a list
03 User Interface:
04 1.User is asked to enter a list
05 2. The user is asked to enter the key, and the program reports the search
06 result. This is repeated so long as the user wants to continue.
07 '''
08
09 myList = eval(input('Enter a list:\n'))
10 print('List:', myList)
11 while True:
12 key = int(input('Enter the number to be searched:'))
13 found = False
14 for index in range(len(myList)):
15 if myList[index] == key:
16 found = True
17 break
18 if found:
19 print(key,' is present in the list at index', index)
20 else:
21 print(key,' is not present in the list')
22 searchAgain = input('Continue another search? say Y/y for yes, N/n for no:')
23 if searchAgain != 'Y' and searchAgain != 'y':
24 break
The result of executing Program 12.1 on a sample input list of size 15 is shown in Fig 12.1.
● The program begins by creating an empty list myList.
● First, the user is prompted to enter a list of numbers. Suppose the user enters the elements 14, 6, 1, 8, 14,
50, 61, 89, 37, 109, 3, 21, 89, 90, 60 to the list myList (line 9).
● The eval() function used in this statement is a built-in function of Python that takes a string comprising an
expression. If it finds a valid expression, it evaluates it and yields the result; otherwise, it raises Syntax Error for a
syntactically incorrect expression.
● So, the myList will be assigned the list [14, 6, 1, 8, 14, 50, 61, 89, 37, 109, 3, 21, 89, 90, 60].
● Next, on the execution of line 12, the user is prompted to enter the key to be searched (say, 37).
● In line 13, the program initially sets the variable found as False, indicating that the key is not found yet.
● Then, it successively compares the key with the elements at index 0, 1, 2, … until the key is found (line 15) or we
reach the end of the list (line 18).
● If the search is successful (i.e., the condition in line 15 yields True), the program returns True along with the index
of the search key.
● Thus, when we searched for key 37 (Fig. 12.2), the program returned True along with index 8. Now the program
displays the following message (line 19):
37 is present in the list at index 8
● However, if, on examining the entire list, the control comes out of the loop without finding the key, we conclude that
the search key does not appear in the list.
● Thus, when we search for key 10 (Fig. 12.2), the following message is displayed (line 21):
10 is not present in the list
>>> Enter a list:
[14, 6, 1, 8, 14, 50, 61, 89, 37, 109, 3, 21, 89, 90, 60]
Lists and Tuples 297

