I am a beginner in Python, so I apologise in advance if my question is very basic or obvious. I am trying to write a function called find(my_list, value) that takes a list, and a value as parameters. The function searches for the value in the list and returns the index at which the first occurrence of the value is found in the list. I want the function to return -1 if the value isn't found in the list.
The catch is that I am unable to use any in-built functions, except for range() and str(). I also cannot use quit() or exit() or break or return statements to exit out of loops.
I am attempting to use a 'for' loop method, as well as a Boolean statement (to control when to stop the loop). I think I am on the right track, but believe there is an issue with my implementation. I am getting the desired output (-1) for when the value is not in the list. But, I cannot seem to get the desired output for when the value is in the list. Any guidance would be appreciated.
def find(my_list, value):
index = 0
valid = False
if value != my_list:
found = -1
for element in my_list:
if element == value:
valid = True
found = index
else:
index += 1
return found
The list:
str_list1 = ['r', 'i', 'n', 'g', 'i', 'n', 'g']
The call to the function:
print(list_function.find(str_list1, 'g'))
print(list_function.find(str_list1, 'z'))
Expected output:
3
-1