简体   繁体   中英

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

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

Use try and except block to get the position of letters in the word.

for letter in words:
try:
    print(letter.index("o"))
except:
    print("not found")
    pass

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM