问题
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