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>You never actually change <code>a</code> because you never modify the global one. You pass it into a function, where it's value is copied into a local variable <code>x</code>. You then modify <code>x</code>, but it doesn't affect <code>a</code>. Here's an alternative:</p>

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

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

a = convert(a)
print(a)

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

<p>What it's doing is returning the local variable <code>x</code>, which is being manipulated and reassigning it to <code>a</code>, thus giving the desired result</p>

python function python-3.x variables if-statement