Succesive running of code reduces letter output everytime


#1

Hi Everybody

I am on the last part of the PygLatin exercise

I am trying to run this code. When I run it the first time, with input (Saurabh), it gave me output as (aurabhsay) which is correct. When I run it again with input (Saurabh), it gave me output as (aurabhsa). When I run it again with input (Saurabh), it gave me output as (aurabhs) and so on.

But instead of new_word = (word + first + pyg)[1:len(new_word)] if I use new_word = (word + first + pyg)[1:], I get the correct output of (aurabhsay) everytime.

Can you please explain what is causing this issue?

It should give me output of (aurabhsay) everytime I input (Saurabh)


pyg = 'ay'

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

if len(original) > 0 and original.isalpha():
    print new_word
else:
    print 'empty'

#2

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

Break it in two steps.

1st..
new_word = (word + first + pyg)

2nd..
then slice and reassign it again to new_word!


#3

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

What is wrong in using it in same statement? The above code works in same statement when I use it without the len(new_word) part


#4

What is wrong in using it in same statement? The above code works in same statement when I use it without the len(new_word) part

Because new_word is not even defined and youre trying to slice it.


#5

well, here:

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

you create a new variable named new_word. Which i set to word + first + pyg which then sliced, but you use length of new_word here. But we haven't created new_word yet? We are in the process of creating new_word, we haven't done it actually yet


#6

Thanks a lot :slight_smile:


#7

I came here to ask a similar question because of the instructions:

Set new_word equal to the slice from the 1st index all the way to the end of new_word. Use [1:len(new_word)] to do this.

We are instructed to len(new word) to slice new_word which is being defined, and it works in the exercise. I was confused but I'm assuming that the slicing is evaluated last, is that correct?


#8

No, code is evaluated from left to right and top to bottom just like reading (but with some exceptions like parentheses)


#9

Then can you explain why

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

works? Seems like a circular reference.


#10

it is, it shouldn't work, can i see your full code?


#11

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