Python 3在函数内计数更新,但值不会在其外部更新

我猜这里有一个范围问题我错过了某个地方.此函数将所有数字平方并将它们相加.如果数字达到1或89,它应该停止,否则继续.这是我的代码:

count = 0
def chain(x,count):
    x = str(x)
    temp = 0
    for let in range(0,len(x)):
        temp = temp + (int(x[let]) ** 2)
    x = temp
    print("\n")
    print(temp)
    if x == 89:
      count = count + 1
      print(count)
    elif x == 1:
      return False
    else:
        chain(x, count)

 chain(145, 0)

  print(count)

问题是,当我在x == 89时打印计数时,我得到1.但是当我在最后打印计数时,它出现为0.我已经看了看,我似乎没有将它设置为任何东西否则,我也尝试添加返回,返回计数,返回True,似乎没有什么可以解决它.如果有人能够指出我的错误,我将非常感激!

最佳答案 解决方案1:

使计数成为一个全局变量

count = 0
def chain(x):
    global count
    x = str(x)
    temp = 0
    for let in range(0,len(x)):
        temp = temp + (int(x[let]) ** 2)
    x = temp
    print("\n")
    print(temp)
    if x == 89:
      count = count + 1
      print(count)
    elif x == 1:
      return False
    else:
        chain(x)

chain(145)

print(count)

解决方案2:
返回计数并在递归调用时接收它.

def chain(x,count):
    x = str(x)
    temp = 0
    for let in range(0,len(x)):
        temp = temp + (int(x[let]) ** 2)
    x = temp
    print("\n")
    print(temp)
    if x == 89:
      count = count + 1
      print(count)
    elif x == 1:
        pass  # you may want to use -1 or something as flag
    else:
      count = chain(x, count)
    return count


print(chain(145,0))
点赞