【问题标题】:how can I solve pyhon error : local variable 'x' referenced before assignment如何解决python错误:赋值前引用的局部变量'x'
【发布时间】:2020-11-23 19:18:12
【问题描述】:
global max_n
max_n = 0

def dfs(_n, cnt, length):
    if cnt == length:
        print(a)
        total = 0
        for i in range(cnt):
            total += int(a[i]) * (10 ** i)
        if total % 30 == 0:
            if total > max_n:
                max_n = total

如果我使用此代码,则if total > max_n: 中存在错误。

即使全局变量max_n在第1行,为什么会出现这个错误?

你能教我如何调试这个错误案例吗?

【问题讨论】:

  • 你在哪里初始化a_n, cnt, length 使用了哪些值?
  • 您的代码返回NameError: name 'a' is not defined。如果你在其他地方定义了a,你应该在你的代码中显示它,并提供这个函数是如何被调用的。

标签: python global-variables local-variables


【解决方案1】:

我已经遇到过这样的问题, 这是因为函数只搜索函数中的变量。 试试这个代码:

max_n = 0

def dfs(_n, cnt, length):
    global max_n
    if cnt == length:
        print(a)
        total = 0
        for i in range(cnt):
            total += int(a[i]) * (10 ** i)
        if total % 30 == 0:
            if total > max_n:
                max_n = total

【讨论】:

  • 这就是我想要的!非常感谢!!
  • 很高兴能为您提供帮助:)
猜你喜欢
  • 2022-06-29
  • 1970-01-01
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 2022-11-19
  • 2020-05-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多