Questions about the exercise titled 'Censor'


#1



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


The code works well but I have few questions. These are:
1. What's the need of the else statement in the code? What condition is it checking?
2. I understood that the 'join' function adds the contents from the list to the 'text', but how the sequence is maintained? Any clear explanation?
3. Why the 'print' statement is not executing?

Thank you.


text = raw_input("Enter something:")
word = raw_input("Enter something:")

def censor(text, word):
    
   
    splited_text = text.split() # spliting large string and  storing in a variable
    x = [] # declaring empty list
    
    for string in splited_text: # iteration through the contents 
        if string == word:
            string = string.replace(word, "*" * len(string)) # replaces the word with *
            x.append(string) # stores the new word in the empty list
        else:
            x.append(string)    #???
   
    text = " ".join(x) #???
    print text # statement not executing
    
    return text


#2

else doesn't check any condition? That is the point of else, its all cases your if and elif (if you would have elif) wouldn't catch

else is needed because if a word in the sentence (text) doesn't require censoring, you still need to append to your list (which contains your new censored sentence)

list contains the right sequence, else takes care of it? All join has to do is joining the list into a string

Your whole function isn't executing, given you never call it

In short, your program splits the string into a list, so we can loop over the word in the sentence, then we use if/else to determine if the current word in the sentence needs censoring, if so, you append asterisks to your list, else simply append the word. This will keep the sentence order intact.

then finally you join the list into a string and return it


#3

Thanks a lot! Confusions cleared.


#4