There are 2 main issues.
The first is that you're not incrementing i
anywhere. i+1
doesn't modify i
, just returns the value of i+1
which you're not placing anywhere. To increment i
you should use i += 1
.
The second is you're not using the externally defined i
variable in your Search function.
To fix this you could either declare it as global in the start of your method, or pass it as a parameter to your function.
Global method (less preferable):
lister=[4,5,1,2,3,6]
i=0
def Search(arr):
global i
if arr[i]==3:
return i
else:
if i>=0 and i<=(len(arr)-2):
i+=1
return Search(arr)
else:
return -1
print(Search(lister))
And the parameter method (which would be preferable):
lister=[4,5,1,2,3,6]
def Search(arr, i=0):
if arr[i]==3:
return i
else:
if i>=0 and i<=(len(arr)-2):
i+=1
return Search(arr, i)
else:
return -1
print(Search(lister))