def linsearch(list, target):
for i in range(0, len(list)):
if (list[i] == target):
return (i)
else:
return ("not in list")
list1 = [1,2,3,4,5]
print(linsearch(list1,1))
This is the python program. Whenever I put target as 1 it returns correct index that is 0, but for all other cases it gives the else case prompt i.e. "not in list"
You sohuld not return inside the
elsestatement. If you have a return in both theifand theelse, you will never proceed to the second iteration of yourforloop.You can instead just ommit the
elsecompletely and just do nothing whenlist[i]does not match yourtarget. And only when your code reaches the ent of theforloop without returning on a match, return the"not in list"value.