Both if-else conditions output are being printed

Question:

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.

Asked By: Uchhashi

||

Answers:

The for loop will iterate across its entire range. I might suggest a while loop that includes a condition to stop early when the desired data is found. Only print out "not found" after you’ve searched the entire list.

i = 0
found = False
while i < len(List) and not found:
  if name==List[i]:
    print(i)
    found = True
  i = i + 1

if not found:
  print("Name not found.")
Answered By: user2212559

It is because at the end of the for-loop the variable i is equal to its last value so 10 here. I think this is what you want (in a proper code):

values = []

for _ in range(10):
    values.append(input("Enter a name: "))

name = input("Enter a name to be searched: ")

if name in values:
    print("Position of name: ", values.index(name))  # starting from 0!
else:
    print("Name not found.")

Explanations:
my_list.index(val) returns the first index of the element val in the list my_list

An implementation could be:

def index(my_list: List, val: Any) -> int:
    """Return the first index of value in the list and -1 if not found."""
    for i, elem in enumerate(my_list):
        if val == elem:
            return i
    return -1
Answered By: Valentin Goldité

Chances are often good that Python already has a function or module that does what you want. In this case, index() does what you want.

Here’s how that might work in your case:

mylist=[]
num = 10

for i in range(num):
    mylist.append(input("Enter a name: "))

name=input("Enter a name to be searched: ")
try:
    print("Position of name: ", mylist.index(name))
except:
    print("Name not found.")
Answered By: dsagman

@jarmod suggested using a for/else loop, which will loop and if it doesn’t encounter a break, will do something with the else. So the below is a direct implementation of that:

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)
        break
else:
    print("Name not found.")

However there are several changes that could be made:

# stay clear of using "List" which is only ever so slightly different
#from the reserved word "list"
my_list = []

# just a fancy syntax for I don't care what point of the loop I'm at, just
# iterate 10 times and do what I say.
for _ in range(10):
    # append the names to the list
    my_list.append(input("Enter a name: "))


find_name = input("Enter a name to be searched: ")
# for each name in my_list, show me the index and the content at that index
for i, name in enumerate(my_list):
    # if the name is == to the name we want
    if name == find_name:
        print("Position of name: ", i)
        # break out of the loop (which isn't a bad thing in python)
        break
else:
    # otherwise, print not found
    print("Name not found.")

The list could go on – there are many ways to skin a cat.

Answered By: Shmack

You can use walrus operator (:=) within one line if else and index increment by 1 to avoid 0 position of the first name:

List = [input("Enter a name: ") for i in range(10)]
print("Position of name: ", List.index(name)+1) if (name := input("Enter a name to be searched: ")) in List else print("Name not found.")

# Enter a name: sam
# Enter a name: jill
# Enter a name: jack
# Enter a name: john
# Enter a name: paul
# Enter a name: chris
# Enter a name: tom
# Enter a name: jerry
# Enter a name: donald
# Enter a name: harry
# Enter a name to be searched: sam
# Position of name:  1

Or this (for readability):

List = [input("Enter a name: ") for i in range(10)]
if (name := input("Enter a name to be searched: ")) in List:
    print("Position of name: ", List.index(name) + 1)
else:
    print("Name not found.")
Answered By: A. N. C.

Here is some code that is close to what you want

List=[1,2,3,4,5,6,7,8,9,10,11]

for i in range(10):
    List[i]=input("Enter a name:").strip()

name=input("Enter a name to be searched:").strip()
if name in List:
    position = List.index(name)
    print("Position of name:", position)
else:
    print("Name not found.")

By saying "in", the program loops to see if the string of name is letter equivalent (each letter and capitalization is the same) to a value within List. This does it the same way as a for loop (to my understanding).

The .strip() functions are used on the input to strip away any "spaces" before and after the user’s input, so you can have more consistent searches. More wiggle room for user error.

By doing your method with a for loop, you are testing each and every index and printing the result each time.

Below is another possible solution you can put under your name = input… This uses the for loop and then compares the number of wrong names against the size of the list. This means that if you have all wrong names, it will be the same size as the length of list and thus not have found the name.

eqSize = 0
for j in range(len(List)):
    if name == List[j]:
        position = j
    else:
        eqSize += 1
if eqSize == len(List):
    print("Name not found.")
else:
    print("Position of name: ", position)

A third solution using the list count() method below.

if List.count(name) == 0:
    print("Name not found.")
else:
    for i in range(len(List)):
        if name==List[i]:
            print("Position of name: ", i)

count() returns an integer with how many times the passed in variable appears within the list. Checking it immediately can save us some time. Otherwise, we can just iterate through the list checking to see if name is there somewhere. This also will cover duplicates.

len(List) is used here often, this makes it easier in the future instead of having to say range(10) for 10 elements, we can just say the length of List. If List has less or more elements, the rest of the code can cope with it and adapt appropriately.

Answered By: MightySmallFry
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.