If I press enter without typing anything in the code I get an error


#1



https://www.codecademy.com/en/courses/python-beginner-2W5v7/1/5?curriculum_id=4f89dab3d788890003000096


If I press enter without typing any letters I get this error:

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


It should show "empty"

The other parts of the code work fine.


pyg = 'ay'

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


#2

If there is no input, then the string is 0 elements long. There is no word[0], even, let alone word[1].

This code is written out of order. The if statement should be on the second line.


#3

Thanks for the reply,

I do not understand what you mean by "there is no word[0]" I have defined first = word[0] and that works fine if I type something in. Also word[1:] works fine if I type something in. Why would these two variables work fine when something is typed in and not when nothing is typed in?

Plus, if I move the "if statement" nothing works.

Many thanks.


I have now changed the code to the following:

"""

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

"""

This works fine if I type something in and if a leave a blank it returns empty but with the following error message

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


#4

An empty string has no index.

word = ""
len(word)
0
word[0]
Traceback (most recent call last):
File "", line 1, in
word[0]
IndexError: string index out of range

Keep working on the order of your statements and check your variables. Go back through the first five steps in Part 1 and be sure to do them in order.


#5

"""

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

"""

Fixed, thanks for the help.


#6

These two lines need to be swapped. Test content before assigning it to word.


#7

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