func 中的 Python 局部变量

标签 python

def test(a):
    if a>1:
        x=0
    elif a<1:
        y=1
    else:
        x=2
    print(x)
    return 0

为什么test(2)可以,但test(0)会引发以下错误?

赋值前引用的局部变量“x”

我猜想当 test(2) x 被定义时,但是运行 test(0) x 是没有定义,但还想了解更多原因

最佳答案

你自己已经回答了。如果a是 0,则elif a<1是真的,所以只有y被定义。

关于func 中的 Python 局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51666000/

相关文章:

python - 迁移到 1.2.5 后 Django 测试失败 - 子模型的主键问题

python - Pandas 群给他人

python - 如何验证字符串是否仅包含字母、数字、下划线和破折号?

python - 矢量化 numpy 掩码设置

python - 在 Windows 上更改 virtualenv 文件夹

python - 这个解的时间复杂度是O(logn)吗?

python - multiprocessing.Queue 的管道损坏错误

python - 通过 "OTHER"python 重命名不太频繁的类别

python - 如何从 python 中的 os.system 中删除 0 表单?

python - python替换错误。 (属性错误 : 'tuple' object has no attribute 'replace' )