Search code examples
pythonpython-3.xlisterror-handlingletter

Error Handling in Python3 - Finding location of specific letters in a list of words


I am running into issues getting my code to run through a list of words and list the location of the letters in the list. It works fine in listing location for the first two words, but when it encounters a word without the specified letter, the code skips. I will paste the problem and my current code as well as current output below.

words = ["dog", "sparrow", "cat", "frog"]

#You may modify the lines of code above, but don't move them! #When you Submit your code, we'll change these lines to #assign different values to the variables.

#This program is supposed to print the location of the 'o' #in each word in the list. However, line 22 causes an #error if 'o' is not in the word. Add try/except blocks #to print "Not found" when the word does not have an 'o'. #However, when the current word does not have an 'o', the #program should continue to behave as it does now.

#Hint: don't worry that you don't know how line 18 works. #All you need to know is that it may cause an error.

#You may not use any conditionals.

#Fix this code!

My Code

for word in words:
print(word.index("o"))

Output

1
5
Traceback (most recent call last):
  File "FindingO.py", line 22, in <module>
    print(word.index("o"))
ValueError: substring not found
Command exited with non-zero status 1

Solution

  • You only need to add try-except block like this:

    words = ["dog", "sparrow", "cat", "frog"]
    for word in words:
        try:
            print(word.index('o'))
        except:
            print("Not found")
            pass