I can’t figure out why my code doesn’t work properly here, it seems to exit the for loop after the except: continue line. What do I do to fix this? (the code executes but the output is always -1 no matter what list/letter combination is fed so nothing is ever being added to the sum_total variable)
sample_list = [
'Black Mirror',
'Breaking Bad', #2
'Stranger Things', #6
'The Leftovers', #2
'How I Met Your Mother' #7 4.25
]
letter = 'e'
def find_average_first_index(input_list, input_letter):
sum_total = 0
for i in input_list:
try:
sum_total += input_list.index(input_letter)
print(sum_total)
**except:
continue**
if sum_total == 0:
return -1
else:
average_value = (sum_total / len(input_list))
return average_value
>Solution :
You are using index on input_list. I think you might want to use it on i.
sum_total += i.index(input_letter)
When you call index method with an element not in the list it will raise ValueError Exception and your code will go to except block and because of the continue there, it will move to next iteration. And because you are using index method on input_list with letter, it will always raise ValueError in this code and that is the reason for the bug in your code.
https://www.w3schools.com/python/ref_string_index.asp
https://www.w3schools.com/python/ref_list_index.asp