Python:函数执行后不保存变量的值

标签 python function python-3.x variables if-statement

我正在尝试将字符串输入(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/

相关文章:

python - 将 block 状序列分成偶数 block ?

python - Django DateTimeField 很幼稚,但 USE_TZ = True

python - 创建前 n 个值的数据框的更有效方法 - python

python - 连接被拒绝——Nginx 到 Python BaseHTTPServer

c++ - 标准库中没有 std::identity 是有原因的吗?

c - 不使用选择排序对三个指针进行排序

javascript - 如何获取输入字段中的最后一个字符/数字?

python - 为什么 bool 是 Python 3 中 int 的子类?

python - 避免 python 范围错误的策略

c - 不返回字符串。这个程序将 123 这样的数字转换为 "One Two Three"这样的单词,为什么最后我什么也没有得到?