I'm new to lists in python and trying to write a linear searching (using only for loop) code where someone:
- inputs and creates a list of 10 names,
- then inputs a particular name - searches the name in the list, if found output of the position is printed otherwise output an error message.
Here is my code:
List=[1,2,3,4,5,6,7,8,9,10,11]
for i in range(10):
List[i]=input("Enter a name: ")
name=input("Enter a name to be searched: ")
for i in range(10):
if name==List[i]:
print("Position of name: ", i)
else:
print("Name not found.")
Whenever I run this module my outputs is:
Example 1:
Enter a name: A
Enter a name: B
Enter a name: C
Enter a name: D
Enter a name: E
Enter a name: F
Enter a name: G
Enter a name: H
Enter a name: I
Enter a name: J
Enter a name to be searched: A
Position of name: 0
Name not found.
Name not found.
Name not found.
Name not found.
Name not found.
Name not found.
Name not found.
Name not found.
Name not found.
Whenever any letter is searched, the position is printed but it outputs "Name not found" the other 9 times since it is in a loop. I'm guessing my error lies in lines 8-14 - but I don't understand how it prints both the statements when there is an else between them.
I so far changed it from my initial code:
List=[1,2,3,4,5,6,7,8,9,10,11]
for i in range(10):
List[i]=input("Enter a name: ")
name=input("Enter a name to be searched: ")
if name==List[i]:
print(i)
else:
print("Name not found.")
I added the for i in range(10): loop as it has to go thru all the indexes. If I don't have the loop, it only outputs the position of the last name entered - so I figured looping it would help.