0

Below is the program written for hailstone sequence.

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)

After debugging this program, I see that object referenced by count that is part of global frame is not getting incremented within the function object hailstone, as per the below observation:

enter image description here

Any reason, why count does not get incremented?

overexchange
  • 13,706
  • 19
  • 106
  • 276

1 Answers1

1

The problem is that the incremented count is local to the function. The count defined in the first line of the code is in global scope

Either

  • Pass it as an argument, i.e. def hailstone(n,count) and call it as hailstone(10,count)
  • Make your count global, by having a line, global count at the starting of your function
Bhargav Rao
  • 45,811
  • 27
  • 120
  • 136