以下是为冰雹序列编写的程序。
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
中没有增加,如下面的观察所示:
任何原因,为什么count
没有增加?
答案 0 :(得分:1)
问题是递增的count
是函数的本地。代码第一行中定义的count
在全局范围内
要么
def hailstone(n,count)
并将其称为hailstone(10,count)
count
行,使global count
为全局