1

I'm using Python to search for the position of an entered name in a list. I use the binary search: compare entered name with the middle-value of the list, if not matched, search in the 1st half list then 2nd half list. When I run following script, IDE shows nothing. Please help me review it:

def search_for_name(name, list):
  midValue = list[int(len(list)/2)]
  x = 0
  if name == midValue:
    x = int(len(list)/2)
    return x
  elif name < midValue:
    while x < int(len(list))/2:
      if list[x] == name:
        return x
      else:
        x += 1
  else:
    x = int(len(list)/2)
    while x <= int(len(list)):
      if list[x] == name:
        return x
      else:
        x += 1
  print('The name you want to search exists in our list. Its position is {}'.format(x))
totten
  • 2,769
  • 3
  • 27
  • 41
Binh Nguyen
  • 31
  • 1
  • 5

1 Answers1

1

You're returning the found value from the function, which means that your print statement will never be called. Instead, use the value returned and then print that:

def search_for_name(name, list):
    ...

pos = search_for_name('matt', ['a', 'b', 'matt', 'x', 'y', 'z'])

if pos is None:
    print("Name was not found")
else:
    print('The name you want to search exists in our list. Its position is {}'.format(pos))
MatsLindh
  • 49,529
  • 4
  • 53
  • 84