Len(word) function breaking after 8 chars


#1

The below script I wrote for the exercise breaks a little if the input is bigger than 8 chars and anything at or over 12 causes runtime errors in the codecademy editor.
I didn’t do anything odd or fancy with len(new_word); would appreciate a second or third set of eyes on this.


pyg = ‘ay’

original = raw_input(‘Enter a word:’)

if len(original) > 0 and original.isalpha():
#takes input and puts lower case version for use
word = original.lower()
#sets first letter of input as a var
first = original[0]
#Makes new word from 1 char to end, then addends the first var
#and the pyg “ay” at the end
new_word = word[1:len(new_word)] + first + pyg
print new_word
else:
print ‘empty’


#2

Can you paste your code in preformatted text? I can’t see what going on.


#3
PYG LATIN SCRIPT

pyg = 'ay'

original = raw_input('Enter a word:')

if len(original) > 0 and original.isalpha():
  #takes input and puts lower case version for use
  word = original.lower()
  #sets first letter of input as a var
  first = original[0]
  #Makes new word from 1 char to end, then addends the first var 
  #and the pyg "ay" at the end
  new_word = word[1:len(new_word)] + first + pyg
  print new_word
else:
  print 'empty'

#4

That’ll raise an error regardless of input length, I suggest reading the error since that explains what’s wrong

$ python2 james.hall851.py 
Enter a word:a
Traceback (most recent call last):
  File "james.hall851.py", line 12, in <module>
    new_word = word[1:len(new_word)] + first + pyg
NameError: name 'new_word' is not defined

#5

Just do:

PYG LATIN SCRIPT

pyg = 'ay'

original = raw_input('Enter a word:')

if len(original) > 0 and original.isalpha():
  #takes input and puts lower case version for use
  word = original.lower()
  #sets first letter of input as a var
  first = original[0]
  #Makes new word from 1 char to end, then addends the first var 
  #and the pyg "ay" at the end
  new_word = word + first + pyg
  new_word = new_word[1:len(new_word)]
  print new_word
else:
  print 'empty'

First concatenate word, first and pyg into the variable new_world
Then slice the new_word variable


#6

Thanks for all the feedback, I got it to run yesterday with “test” but then it broke and I didn’t get the feedback about line 12 at that time.

I have since changed it to
new_word = word[1:len(original)] + first + pyg

and it’s up and working


#7

Sure, but, use the strings’s own length, not another string’s length.

Let nothing be by coincidence, argue for why everything should be the way it is, refer to what action you’re trying to describe (for example, that would tell you which length to use)
If you try something and it seems to work but you can’t argue for it, then it’s almost certainly wrong.


#8

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