+ 2
I need help tweaking my linear search algorithm
I've written a linear search algorithm, but towards the end where I try to call the function for it, it gives me no output. have I done anything wrong? [update]: I've fixed the output, but now I have a problem where the the only value that can be found within the algorithm is 2. any suggestions on how to change this https://code.sololearn.com/czSas3t1uoS4/?ref=app
1 Answer
+ 3
"""
You need at least to desindent the 'return' statement, as else you break the loop after the first item was tested...
Anyway, if you want get the result as returned value of your function you must add a 'return' statement of your 'x' local variable, indented so that it was in the 'if' condirional block:
"""
def linear_search(my_list,tv):
for x in range(0,len(my_list)):
if my_list[x] == tv:
print(tv,"was found at index",x)
return x
return -1
my_list = [2,5,9,54,21,69,41]
loc = linear_search(my_list,9)
print(loc)