Pig latin translator bug?


#1




Sometimes when it cuts, it cuts till the 2nd last letter and doesn't include the last letter.


Since it's the same code, I expect it to be correct 100% but sometimes it doesn't print the last letter of the word I input into the console. I'm new to python or coding in general, can someone please help explain this to me?


pyg = 'ay'

original = raw_input('Enter a word:')

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

    print original
    print new_word
    
else:
    print 'empty'


#2

I think the problem is that you need to introduce the variable new_word and set it equal to something on the line before

new_word = word[1:len(new_word)] + first + pyg

I know your error message says that new_word is not a variable it knows, so the way that the computer interprets the code must have to do with the variable being initialized first.
Try putting this line:
new_word = word + first + pyg
directly before

new_word = word[1:len(new_word)] + first + pyg

I hope this helps, let me know. :slight_smile:


#3

Ayy that fixed it! Thank youu

I did had that new_word is not a variable error at some point. (The error somehow disappeared after a while and it keeps bugging out by not printing out a letter)

However, I'm not sure I am following you about the initialising part. Could you please explain it again?


#4

I'm glad that it fixed it.
Initializing a variable means to introduce it, which is what you're doing when you first set something equal to that variable. The reason that you were getting the error, is because the first time that you mentioned the variable, it was this line:

new_word = word[1:len(new_word)] + first + pyg

This is a problem, (I didn't see it at first when looking through your code, but now I do), because you're referencing new_word in the slice you're taking . (word[1:len(new_word)]). You are trying to use the length of new_word, but it doesn't have a length yet because it hasn't been introduced before. Does that make sense? The line that I gave you worked because it was what the lesson had already told you to right, but you had to keep it there for the purpose of finding the length of new_word.
Sorry if this sounds really scrambled and unintelligent, I'm not the best explainer.


#5

ohhh yea that makes sense.

With that code it introduced the variable and then it got reassigned? So pretty much I can put anything in that variable like
new_word = "hi"
new_word = word[1:len(new_word)] + first + pyg

This seems a bit messy though hahaha, are there many more ways to introduced a variable?


#6

No, this doesn't work because your taking part of the string of new_word when you slice it.


#7

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