a mistake I keep having with for loops and return statements
<p>I have been noticing a problem I am having whenever I try to make a function that takes changes a string or a list then returns it. </p>

<p>I will give you an example of this happening with a code I just wrote:</p>

<pre><code>def remove_exclamation(string):
string.split(' ')
for i in string:
    i.split()
    for char in i:
        if char == '!':
            del char
            ''.join(i)
            ' '.join(string)
return string
</code></pre>

<p>For instance, I create this code to take a string as its parameter, remove any exclamation in it, the return it changed. The input and output should look like this:</p>

<pre><code>&gt;&gt;&gt;remove_exclamation('This is an example!')
'This is an example'
</code></pre>

<p>But instead I get this:</p>

<pre><code>&gt;&gt;&gt;remove_exclamation('This is an example!')
'This is an example!'
</code></pre>

<p>The function is not removing the exclamation in the output, and is not doing what I intended for it to day.</p>

<p>How can I keep avoiding this when I make for loops, nested for loops etc?</p>

<p>You write your code and formulate your question as if it was possible to modify strings in Python. <strong>It is not possible.</strong></p>

<p>Strings are immutable. All functions which operate on strings return new strings. They do not modify existing strings.</p>

<p>This returns a list of strings, but you are not using the result:</p>

<pre><code>string.split(' ')
</code></pre>

<p>This also:</p>

<pre><code>i.split()
</code></pre>

<p>This deletes the variable named <code>char</code>. It does not affect the char itself:</p>

<pre><code>        del char
</code></pre>

<p>This creates a new string which you do not use:</p>

<pre><code>        ''.join(i)
</code></pre>

<p>This also:</p>

<pre><code>        ' '.join(string)
</code></pre>

<p>All in all, almost every line of the code is wrong.</p>

<p>You probably wanted to do this:</p>

<pre><code>def remove_exclamation(string):
    words = string.split(' ')
    rtn_words = []
    for word in words:
        word_without_exclamation = ''.join(ch for ch in word if ch != '!')
        rtn_words.append(word_without_exclamation)
    return ' '.join(rtn_words)
</code></pre>

<p>But in the end, this does the same thing:</p>

<pre><code>def remove_exclamation(string):
    return string.replace('!', '')
</code></pre>

python python-3.x for-loop return return-value