Python: Function not holding the value of a variable after execution
<p>I'm trying to convert a string input (y/n) into an integer (1/0). The function appears to be working, as when the 'convert' function is executed using 'a' as an argument, the argument is printed inside the function, however printing outside the function uses the original value of the variable 'a'. I've tried using return inside the 'convert' function, but this appears to have no affect. </p>

<pre><code>a = input("Are you happy?(y/n)")

def convert(x):
    if x == ('y'):
        x = 1
    if x == ('n'):
        x = 0
    print (x)

convert(a)
print (a)

&gt;&gt;&gt; Are you happy?(y/n)y
1
y
</code></pre>

<p>That is because you are not changing <code>a</code> at all. You are simply passing <code>a</code> to the <code>convert</code> method, but this will not actually <em>change</em> what is in <code>a</code>. In order to change <code>a</code>, you need to assign <code>a</code> to the result of what <code>convert</code> will do. Like this:</p>

<pre><code>a = convert(a)
</code></pre>

<p>This is now where you will need that <code>return</code>, since you have to actually return something from the <code>convert</code> method in order to change the value of what <code>a</code> will now hold.</p>

<p>So, taking all that in to account, you will now have: </p>

<pre><code>a = input("Are you happy?(y/n)")
def convert(x):
    if x == ('y'):
        x = 1
    if x == ('n'):
        x = 0
    print (x)
    # add the return here to return the value
    return x

# Here you have to assign what the new value of a will be
a = convert(a)
print(a)
</code></pre>

<p>Output:</p>

<pre><code>1
1
</code></pre>

python function python-3.x variables if-statement