我正在尝试将字符串输入(y/n)转换为整数(1/0)。该函数似乎正在工作,因为当使用“a”作为参数执行“convert”函数时,参数在函数内部打印,但是在函数外部打印使用变量“a”的原始值。我尝试在“转换”函数中使用 return,但这似乎没有影响。
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
最佳答案
那是因为您根本没有更改a
。您只需将 a
传递给 convert
方法,但这实际上不会a
中的内容改变。为了更改 a
,您需要将 a
分配给 convert
的结果。像这样:
a = convert(a)
现在您需要 return
,因为您必须从 convert
方法实际返回一些内容,才能更改 a 的值
现在将成立。
因此,考虑到所有这些,您现在将拥有:
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)
输出:
1
1
关于Python:函数执行后不保存变量的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39176982/