10. censor


#1



https://www.codecademy.com/courses/python-intermediate-en-rCQKw/1/4?curriculum_id=4f89dab3d788890003000096#


Okay so I solved this exercise, but it took me a million tries. Clearly I'm not understanding something here.

Why does the second section of code (correct answer I passed with) work, but the first one does not?

In both cases, I am trying to iterate through the list (created when I used the .split() function on my string) and if an individual element is equal to 'word', then set that element equal to a number of asterisks equal to its length.

Is it because you can't re-dfine the element in the first example of code (using the for item in list) method but you can in the second (using the for i in range(0, len(list))? My best guess is it's something to do with that...


def censor(text, word):
    newtext = text.split()
    for element in newtext:
        if element == word:
            element = "*"*len(element)
        return " ".join(newtext)

---------------------------------------

def censor(text, word):
    newtext = text.split()
    for i in range(0,len(newtext)):
        if newtext[i] == word:
            newtext[i] = "*" * len(newtext[i])
    return " ".join(newtext)


#2

yes, but there is a huge difference, the two loops are very different. in the first code element is just variable which exist only inside the loop, and in each run of the loop gets assigned a new value, it isn't stored anywhere (and cease to exist after the loops end)

in the second code, you use range() which gives you indexes, and you use this indexes to insert a censored version of the word in the newtext list.

Your guess is pretty good. and the indent of return is not good in your first code, a function ends the moment a return keyword is reached, which in the first code is in the first run of the loop


#3

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