Python: exception of type index error?

爷,独闯天下 提交于 2021-01-28 15:29:31

问题


I have to write small sections of code for an introductory programming class I'm taking - I had no trouble until I tried this one. The code works fine so far as I can tell but I keep getting the IndexError, can anyone tell me what I'm missing?

vowel = {"a", "e", "o", "i", "u", "A", "E", "I", "O", "U"}
word = input("Enter a phrase: ")

if word[0] in vowel:
    print("an", word)
else:
    print("a", word)

EDIT: The code's working perfectly now, all I needed was the additional if statement for an empty string, as per your suggestions


回答1:


I am not sure what exact error you are getting. You mention IndexError which would normally be raised for an index that is out of range. In your code, the only place where I could see such problem might exist is word[0]. But that would only happen if no word has been entered. I assume that your code is just an example and that a word is always entered.

You are also defining a set (vowel) using the curly braces notation and that might be a problem for some old python (before 2.7).

EDIT:

Based on your comment I'm pretty sure it is actually about the word not being entered. So, no to solve your test problem for you completely, I will just say that you should consider the case when word is empty in your program as well.




回答2:


You probably need to check for null input, meaning the test system is just hitting enter rather than entering an actual string. When you try to index the first character of an empty string you will get an index error. Try something similar to:

vowel = {"a", "e", "o", "i", "u", "A", "E", "I", "O", "U"}
word = input("Enter a phrase: ")
if word == "":
    print("please enter a word")
elif word[0] in vowel:
    print("an", word)
else:
    print("a", word)

You should check if the assignment has any instructions on how to handle empty strings.



来源:https://stackoverflow.com/questions/32021740/python-exception-of-type-index-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!