查询python中的hailstone序列程序

时间:2015-02-02 10:17:05

标签: python

以下是为冰雹序列编写的程序。

count = 0

def hailstone(n):
    """Print the terms of the 'hailstone sequence' from n to 1."""
    assert n > 0
    print(n)
    if n > 1:
        if n % 2 == 0:
            hailstone(n / 2)
        else:
            hailstone((n * 3) + 1)
    count = count + 1
    return count

hailstone(10)

在调试这个程序之后,我发现作为全局框架一部分的count引用的对象在函数对象hailstone中没有增加,如下面的观察所示:

enter image description here

任何原因,为什么count没有增加?

1 个答案:

答案 0 :(得分:1)

问题是递增的count是函数的本地。代码第一行中定义的count在全局范围内

要么

  • 将其作为参数传递,即def hailstone(n,count)并将其称为hailstone(10,count)
  • 在功能开始时设置count行,使global count为全局