Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python exercise using try/except with continue

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading