Ending up: how does defining new_word work?


#1


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


My code works correctly but I want to know why defining new_word twice, works.

First I define new word which is: new_word = word + first + pyg then in the next line I slice the first letter off of new_word, which then creates word + first + pyg correctly. What makes it keep the sliced part rather than the first definition of new_word?


pyg = 'ay'

original = raw_input('Enter a word:')

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


#2

You use = which overwrites the memory address new_word was looking at. However until it has finished running you can call what new_word is/used to be looking at.


#3

Sorry, I'm not sure that I get it. By using '=' I overwrite what new_word is - ok that's fine, but why doesn't it just print the slice section of: new_word[1:len(new_word)]. It still goes back and adds it to the first + pyg.

Thanks!


#4

It still goes back and adds it to the first + pyg.

It doesn't when you create new_word is doesn't just reference the other variables, it creates a new string in memory containing everything and new_word points to it. When you then slice it, you use that newly created string and create another string that only contains the slice and new_word then points to that.

>>> new_word = word + first + pyg 
>>> print new_word
testtay

>>> print word
test

>>> word = "done" # change the variable word's value from "test" to "done"

>>> print new_word # print new_word but it hasn't changed, even though we changed word.
testtay

>>> print new_word[1:len(new_word)]
esttay

>>> new_word = new_word[1:len(new_word)]
>>> print new_word
esttay

Hopefully that will make it more clear. This is wil original ="test".


#5

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