【问题标题】:I've attached my code. Please review it and tell me the reason of the error. Explain it? [duplicate]我附上了我的代码。请检查它并告诉我错误的原因。解释一下? [复制]
【发布时间】:2021-03-15 02:47:59
【问题描述】:

我的代码

x = 10
def fun():
    x = x + 2
    print(x)
fun()
print(x)

还有输出错误

UnboundLocalError:赋值前引用了局部变量“x”

【问题讨论】:

    标签: python python-3.x debugging error-handling


    【解决方案1】:

    您尝试在函数fun() 中修改的变量x 是全局范围的。因此,您不能像这样在函数内部访问它。但是,您可以使用:

    x = 10
    def fun():
        global x
        x = x + 2
        print(x)
    fun()
    print(x)
    

    附加global x,将允许函数修改全局范围内的变量x

    【讨论】:

      【解决方案2】:

      您没有将 x 作为函数的参数。这就是为什么。

      x = 10
      def fun(x):
          x = x + 2
          print(x)
      fun()
      print(x)
      

      【讨论】:

      • 看看我可以选择什么类型以及如何定义一个函数。我可以定义一个没有参数的函数...
      【解决方案3】:

      您必须在 def fun() 中传递全局 x,因为在 fun() 中没有分配名为 x 的变量。代码如下:

      x = 10
      def fun():
          global x
          x = x + 2
          print(x)
      fun()
      print(x)
      

      输出

      >>> 12
      >>> 12
      

      您也可以简单地传递一个参数,但这会影响 x 的值:

      x = 10
      def fun(x):
          x = x + 2
          print(x)
      fun(x)
      print(x)
      

      输出

      >>> 12
      >>> 10
      

      【讨论】:

        猜你喜欢
        • 2014-05-29
        • 1970-01-01
        • 2020-07-23
        • 2021-10-04
        • 1970-01-01
        • 1970-01-01
        • 2020-09-06
        • 1970-01-01
        • 2022-08-06
        相关资源
        最近更新 更多