Translator Errors When You Leave It Blank


#1



3.11 Testing, Testing...


The course counts my code as working, and I don't have a problem when I put in an actual word, but when I leave the box empty, I get an error:

Traceback (most recent call last):
File "python", line 4, in
IndexError: string index out of range

I anticipated the code would print empty when I didn't put a word in because it's character count is < 0 and wouldn't be considered a letter, so it wouldn't reach the conclusion of the if-and statement. Instead, I'm getting the above syntax error. Is it because of where I placed it in the code? Any explanation will do.


original = raw_input('Enter a word:')
pyg = 'ay'
word = original.lower()
first = word[0]
new_word = word + first + pyg
new_word = new_word[1:len(new_word)]
if len(original) > 0 and original.isalpha():
    print new_word.lower()
else:
    print 'empty'

Many thanks.


#2

Please check my other post first.
This all:

word = original.lower()
first = word[0]
new_word = word + first + pyg
new_word = new_word[1:len(new_word)]

Should go under the if statement as the commands should only be done if the input of the user meets the criteria. Also you may consider putting this all under a function, although the result should be same either way.


#3

Sorry I just read your question into more detail after my first post. To answer your question, yes:

You see, by your code, Python will first try to initiate the Translator, as you don't put the criteria the original input should fit until later. If it gets a blank input, it will get stuck here:

first = word[0]

As a blank string will have no index, so Python will be stuck there, which is where your error message is coming from. If you first list the criteria, then do the commands like I have said in the above post, then it will print "empty" as it is suppose to. Hope you understand now. Let me know if you still need help. :slight_smile:

-- @chipjumper36731


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.