James Wilkinson James Wilkinson - 3 months ago 9
Python Question

Python: Function not holding the value of a variable after execution

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.

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)

>>> Are you happy?(y/n)y
1
y

Answer

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

a = convert(a)

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

So, taking all that in to account, you will now have:

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)

Output:

1
1
Comments